lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
token-metadata/program/tests/freeze_delegated_account.rs
levicook/metaplex-program-library
5d13c31fec61651937033d26c295b9851da4b62d
#![cfg(feature = "test-bpf")] mod utils; use mpl_token_metadata::error::MetadataError; use num_traits::FromPrimitive; use solana_program_test::*; use solana_sdk::{ instruction::InstructionError, signature::{Keypair, Signer}, transaction::{Transaction, TransactionError}, transport::TransportError, }; use utils::*; mod freeze_delegated { use super::*; #[tokio::test] async fn freeze_delegated_token_success() { let mut context = program_test().start_with_context().await; let freeze_authority = &context.payer.pubkey(); let delegate = Keypair::new(); let test_metadata = Metadata::new(); test_metadata .create_v2( &mut context, "Test".to_string(), "TST".to_string(), "uri".to_string(), None, 10, false, Some(freeze_authority), None, None, ) .await .unwrap(); let test_master_edition = MasterEditionV2::new(&test_metadata); test_master_edition .create_v3(&mut context, Some(1)) .await .unwrap(); let approve_ix = spl_token::instruction::approve(&spl_token::id(), &test_metadata.token.pubkey(), &delegate.pubkey(), &context.payer.pubkey(), &[], 1).unwrap(); let approve_tx = Transaction::new_signed_with_payer( &[approve_ix], Some(&context.payer.pubkey()), &[&context.payer], context.last_blockhash, ); context .banks_client .process_transaction(approve_tx) .await .unwrap(); let freeze_tx = Transaction::new_signed_with_payer( &[mpl_token_metadata::instruction::freeze_delegated_account( mpl_token_metadata::id(), delegate.pubkey(), test_metadata.token.pubkey(), test_master_edition.pubkey, test_master_edition.mint_pubkey, )], Some(&context.payer.pubkey()), &[&context.payer, &delegate], context.last_blockhash, ); context .banks_client .process_transaction(freeze_tx) .await .unwrap(); let transfer_ix = spl_token::instruction::transfer(&spl_token::id(), &test_metadata.token.pubkey(), &test_metadata.token.pubkey(), &context.payer.pubkey(), &[], 1).unwrap(); let transfer_tx = Transaction::new_signed_with_payer( &[transfer_ix], Some(&context.payer.pubkey()), &[&context.payer], context.last_blockhash, ); let err = context .banks_client .process_transaction(transfer_tx) .await .unwrap_err(); assert_custom_error!(err, spl_token::error::TokenError::AccountFrozen); } #[tokio::test] async fn freeze_delegated_no_freeze_authority() { let mut context = program_test().start_with_context().await; let freeze_authority = &context.payer.pubkey(); let delegate = Keypair::new(); let test_metadata = Metadata::new(); test_metadata .create_v2( &mut context, "Test".to_string(), "TST".to_string(), "uri".to_string(), None, 10, false, Some(freeze_authority), None, None, ) .await .unwrap(); spl_token::instruction::approve(&spl_token::id(), &test_metadata.token.pubkey(), &delegate.pubkey(), &context.payer.pubkey(), &[], 1).unwrap(); let freeze_ix = mpl_token_metadata::instruction::freeze_delegated_account( mpl_token_metadata::id(), delegate.pubkey(), test_metadata.token.pubkey(), test_metadata.pubkey, test_metadata.mint.pubkey(), ); let freeze_tx = Transaction::new_signed_with_payer( &[freeze_ix], Some(&context.payer.pubkey()), &[&context.payer, &delegate], context.last_blockhash, ); let err = context .banks_client .process_transaction(freeze_tx) .await .unwrap_err(); assert_custom_error!(err, MetadataError::InvalidFreezeAuthority); } #[tokio::test] async fn freeze_delegated_token_not_delegated() { let mut context = program_test().start_with_context().await; let freeze_authority = &context.payer.pubkey(); let _delegate = Keypair::new(); let test_metadata = Metadata::new(); test_metadata .create_v2( &mut context, "Test".to_string(), "TST".to_string(), "uri".to_string(), None, 10, false, Some(freeze_authority), None, None, ) .await .unwrap(); let test_master_edition = MasterEditionV2::new(&test_metadata); test_master_edition .create_v3(&mut context, None) .await .unwrap(); let freeze_ix = mpl_token_metadata::instruction::freeze_delegated_account( mpl_token_metadata::id(), context.payer.pubkey(), test_metadata.token.pubkey(), test_master_edition.pubkey, test_master_edition.mint_pubkey, ); let freeze_tx = Transaction::new_signed_with_payer( &[freeze_ix], Some(&context.payer.pubkey()), &[&context.payer], context.last_blockhash, ); let err = context .banks_client .process_transaction(freeze_tx) .await .unwrap_err(); assert_custom_error!(err, MetadataError::InvalidDelegate); } #[tokio::test] async fn freeze_delegated_token_try_thaw() { let mut context = program_test().start_with_context().await; let freeze_authority = &context.payer.pubkey(); let delegate = Keypair::new(); let test_metadata = Metadata::new(); test_metadata .create_v2( &mut context, "Test".to_string(), "TST".to_string(), "uri".to_string(), None, 10, false, Some(freeze_authority), None, None, ) .await .unwrap(); let test_master_edition = MasterEditionV2::new(&test_metadata); test_master_edition .create_v3(&mut context, None) .await .unwrap(); spl_token::instruction::approve(&spl_token::id(), &test_metadata.token.pubkey(), &delegate.pubkey(), &context.payer.pubkey(), &[], 1).unwrap(); let freeze_ix = mpl_token_metadata::instruction::freeze_delegated_account( mpl_token_metadata::id(), delegate.pubkey(), test_metadata.token.pubkey(), test_master_edition.pubkey, test_master_edition.mint_pubkey, ); let _freeze_tx = Transaction::new_signed_with_payer( &[freeze_ix], Some(&context.payer.pubkey()), &[&context.payer, &delegate], context.last_blockhash, ); let thaw_ix = mpl_token_metadata::instruction::thaw_delegated_account( mpl_token_metadata::id(), context.payer.pubkey(), test_metadata.token.pubkey(), test_master_edition.pubkey, test_master_edition.mint_pubkey, ); let thaw_tx = Transaction::new_signed_with_payer( &[thaw_ix], Some(&context.payer.pubkey()), &[&context.payer], context.last_blockhash, ); let err = context .banks_client .process_transaction(thaw_tx) .await .unwrap_err(); assert_custom_error!(err, MetadataError::InvalidDelegate); } }
#![cfg(feature = "test-bpf")] mod utils; use mpl_token_metadata::error::MetadataError; use num_traits::FromPrimitive; use solana_program_test::*; use solana_sdk::{ instruction::InstructionError, signature::{Keypair, Signer}, transaction::{Transaction, TransactionError}, transport::TransportError, }; use utils::*; mod freeze_delegated { use super::*; #[tokio::test] async fn freeze_delegated_token_success() { let mut context = program_test().start_with_context().await; let freeze_authority = &context.payer.pubkey(); let delegate = Keypair::new(); let test_metadata = Metadata::new(); test_metadata .create_v2( &mut context, "Test".to_string(), "TST".to_string(), "uri".to_string(), None, 10, false, Some(freeze_authority), None, None, ) .await .unwrap(); let test_master_edition = MasterEditionV2::new(&test_metadata); test_master_edition .create_v3(&mut context, Some(1)) .await .unwrap(); let approve_ix = spl_token::instruction::approve(&spl_token::id(), &test_metadata.token.pubkey(), &delegate.pubkey(), &context.payer.pubkey(), &[], 1).unwrap(); let approve_tx = Transaction::new_signed_with_payer( &[approve_ix], Some(&context.payer.pubkey()), &[&context.payer], context.last_blockhash, ); context .banks_client .process_transaction(approve_tx) .await .unwrap(); let freeze_tx = Transaction::new_signed_with_paye
#[tokio::test] async fn freeze_delegated_no_freeze_authority() { let mut context = program_test().start_with_context().await; let freeze_authority = &context.payer.pubkey(); let delegate = Keypair::new(); let test_metadata = Metadata::new(); test_metadata .create_v2( &mut context, "Test".to_string(), "TST".to_string(), "uri".to_string(), None, 10, false, Some(freeze_authority), None, None, ) .await .unwrap(); spl_token::instruction::approve(&spl_token::id(), &test_metadata.token.pubkey(), &delegate.pubkey(), &context.payer.pubkey(), &[], 1).unwrap(); let freeze_ix = mpl_token_metadata::instruction::freeze_delegated_account( mpl_token_metadata::id(), delegate.pubkey(), test_metadata.token.pubkey(), test_metadata.pubkey, test_metadata.mint.pubkey(), ); let freeze_tx = Transaction::new_signed_with_payer( &[freeze_ix], Some(&context.payer.pubkey()), &[&context.payer, &delegate], context.last_blockhash, ); let err = context .banks_client .process_transaction(freeze_tx) .await .unwrap_err(); assert_custom_error!(err, MetadataError::InvalidFreezeAuthority); } #[tokio::test] async fn freeze_delegated_token_not_delegated() { let mut context = program_test().start_with_context().await; let freeze_authority = &context.payer.pubkey(); let _delegate = Keypair::new(); let test_metadata = Metadata::new(); test_metadata .create_v2( &mut context, "Test".to_string(), "TST".to_string(), "uri".to_string(), None, 10, false, Some(freeze_authority), None, None, ) .await .unwrap(); let test_master_edition = MasterEditionV2::new(&test_metadata); test_master_edition .create_v3(&mut context, None) .await .unwrap(); let freeze_ix = mpl_token_metadata::instruction::freeze_delegated_account( mpl_token_metadata::id(), context.payer.pubkey(), test_metadata.token.pubkey(), test_master_edition.pubkey, test_master_edition.mint_pubkey, ); let freeze_tx = Transaction::new_signed_with_payer( &[freeze_ix], Some(&context.payer.pubkey()), &[&context.payer], context.last_blockhash, ); let err = context .banks_client .process_transaction(freeze_tx) .await .unwrap_err(); assert_custom_error!(err, MetadataError::InvalidDelegate); } #[tokio::test] async fn freeze_delegated_token_try_thaw() { let mut context = program_test().start_with_context().await; let freeze_authority = &context.payer.pubkey(); let delegate = Keypair::new(); let test_metadata = Metadata::new(); test_metadata .create_v2( &mut context, "Test".to_string(), "TST".to_string(), "uri".to_string(), None, 10, false, Some(freeze_authority), None, None, ) .await .unwrap(); let test_master_edition = MasterEditionV2::new(&test_metadata); test_master_edition .create_v3(&mut context, None) .await .unwrap(); spl_token::instruction::approve(&spl_token::id(), &test_metadata.token.pubkey(), &delegate.pubkey(), &context.payer.pubkey(), &[], 1).unwrap(); let freeze_ix = mpl_token_metadata::instruction::freeze_delegated_account( mpl_token_metadata::id(), delegate.pubkey(), test_metadata.token.pubkey(), test_master_edition.pubkey, test_master_edition.mint_pubkey, ); let _freeze_tx = Transaction::new_signed_with_payer( &[freeze_ix], Some(&context.payer.pubkey()), &[&context.payer, &delegate], context.last_blockhash, ); let thaw_ix = mpl_token_metadata::instruction::thaw_delegated_account( mpl_token_metadata::id(), context.payer.pubkey(), test_metadata.token.pubkey(), test_master_edition.pubkey, test_master_edition.mint_pubkey, ); let thaw_tx = Transaction::new_signed_with_payer( &[thaw_ix], Some(&context.payer.pubkey()), &[&context.payer], context.last_blockhash, ); let err = context .banks_client .process_transaction(thaw_tx) .await .unwrap_err(); assert_custom_error!(err, MetadataError::InvalidDelegate); } }
r( &[mpl_token_metadata::instruction::freeze_delegated_account( mpl_token_metadata::id(), delegate.pubkey(), test_metadata.token.pubkey(), test_master_edition.pubkey, test_master_edition.mint_pubkey, )], Some(&context.payer.pubkey()), &[&context.payer, &delegate], context.last_blockhash, ); context .banks_client .process_transaction(freeze_tx) .await .unwrap(); let transfer_ix = spl_token::instruction::transfer(&spl_token::id(), &test_metadata.token.pubkey(), &test_metadata.token.pubkey(), &context.payer.pubkey(), &[], 1).unwrap(); let transfer_tx = Transaction::new_signed_with_payer( &[transfer_ix], Some(&context.payer.pubkey()), &[&context.payer], context.last_blockhash, ); let err = context .banks_client .process_transaction(transfer_tx) .await .unwrap_err(); assert_custom_error!(err, spl_token::error::TokenError::AccountFrozen); }
function_block-function_prefixed
[ { "content": "/// Strings need to be appended with `\\0`s in order to have a deterministic length.\n\n/// This supports the `memcmp` filter on get program account calls.\n\n/// NOTE: it is assumed that the metadata fields are never larger than the respective MAX_LENGTH\n\npub fn puff_out_data_fields(metadata: ...
Rust
linkerd/proxy/api-resolve/src/resolve.rs
tegioz/linkerd2-proxy
8b6f9a09968ca844e5c7bcbf924c045d4797541b
use crate::api::destination as api; use crate::core::resolve::{self, Update}; use crate::metadata::Metadata; use crate::pb; use futures::{future, try_ready, Future, Poll, Stream}; use tower::Service; use tower_grpc::{self as grpc, generic::client::GrpcService, Body, BoxBody}; use tracing::{debug, trace}; #[derive(Clone)] pub struct Resolve<S> { service: api::client::Destination<S>, scheme: String, context_token: String, } pub struct Resolution<S: GrpcService<BoxBody>> { inner: grpc::Streaming<api::Update, S::ResponseBody>, } impl<S> Resolve<S> where S: GrpcService<BoxBody> + Clone + Send + 'static, S::ResponseBody: Send, <S::ResponseBody as Body>::Data: Send, S::Future: Send, { pub fn new<T>(svc: S) -> Self where Self: resolve::Resolve<T>, { Self { service: api::client::Destination::new(svc), scheme: "".into(), context_token: "".into(), } } pub fn with_scheme<T: ToString>(self, scheme: T) -> Self { Self { scheme: scheme.to_string(), ..self } } pub fn with_context_token<T: ToString>(self, context_token: T) -> Self { Self { context_token: context_token.to_string(), ..self } } } impl<T, S> Service<T> for Resolve<S> where T: ToString, S: GrpcService<BoxBody> + Clone + Send + 'static, S::ResponseBody: Send, <S::ResponseBody as Body>::Data: Send, S::Future: Send, { type Response = Resolution<S>; type Error = grpc::Status; type Future = future::Map< grpc::client::server_streaming::ResponseFuture<api::Update, S::Future>, fn(grpc::Response<grpc::Streaming<api::Update, S::ResponseBody>>) -> Resolution<S>, >; fn poll_ready(&mut self) -> Poll<(), Self::Error> { self.service.poll_ready() } fn call(&mut self, target: T) -> Self::Future { let path = target.to_string(); trace!("resolve {:?}", path); self.service .get(grpc::Request::new(api::GetDestination { path, scheme: self.scheme.clone(), context_token: self.context_token.clone(), })) .map(|rsp| { debug!(metadata = ?rsp.metadata()); Resolution { inner: rsp.into_inner(), } }) } } impl<S> resolve::Resolution for Resolution<S> where S: GrpcService<BoxBody>, { type Endpoint = Metadata; type Error = grpc::Status; fn poll(&mut self) -> Poll<Update<Self::Endpoint>, Self::Error> { loop { match try_ready!(self.inner.poll()) { Some(api::Update { update }) => match update { Some(api::update::Update::Add(api::WeightedAddrSet { addrs, metric_labels, })) => { let addr_metas = addrs .into_iter() .filter_map(|addr| pb::to_addr_meta(addr, &metric_labels)) .collect::<Vec<_>>(); if !addr_metas.is_empty() { return Ok(Update::Add(addr_metas).into()); } } Some(api::update::Update::Remove(api::AddrSet { addrs })) => { let sock_addrs = addrs .into_iter() .filter_map(pb::to_sock_addr) .collect::<Vec<_>>(); if !sock_addrs.is_empty() { return Ok(Update::Remove(sock_addrs).into()); } } Some(api::update::Update::NoEndpoints(api::NoEndpoints { exists })) => { let update = if exists { Update::Empty } else { Update::DoesNotExist }; return Ok(update.into()); } None => {} }, None => return Err(grpc::Status::new(grpc::Code::Ok, "end of stream")), }; } } }
use crate::api::destination as api; use crate::core::resolve::{self, Update}; use crate::metadata::Metadata; use crate::pb; use futures::{future, try_ready, Future, Poll, Stream}; use tower::Service; use tower_grpc::{self as grpc, generic::client::GrpcService, Body, BoxBody}; use tracing::{debug, trace}; #[derive(Clone)] pub struct Resolve<S> { service: api::client::Destination<S>, scheme: String, context_token: String, } pub struct Resolution<S: GrpcService<BoxBody>> { inner: grpc::Streaming<api::Update, S::ResponseBody>, } impl<S> Resolve<S> where S: GrpcService<BoxBody> + Clone + Send + 'static, S::ResponseBody: Send, <S::ResponseBody as Body>::Data: Send, S::Future: Send, { pub fn new<T>(svc: S) -> Self where Self: resolve::Resolve<T>, { Self { service: api::client::Destination::new(svc), scheme: "".into(), context_token: "".into(), } } pub fn with_scheme<T: ToString>(self, scheme: T) -> Self { Self { scheme: scheme.to_string(), ..self } } pub fn with_context_token<T: ToString>(self, context_token: T) -> Self { Self { context_token: context_token.to_string(), ..self } } } impl<T, S> Service<T> for Resolve<S> where T: ToString, S: GrpcService<BoxBody> + Clone + Send + 'static, S::ResponseBody: Send, <S::ResponseBody as Body>::Data: Send, S::Future: Send, { type Response = Resolution<S>; type Error = grpc::Status; type Future = future::Map< grpc::client::server_streaming::ResponseFuture<api::Update, S::Future>, fn(grpc::Response<grpc::Streaming<api::Update, S::ResponseBody>>) -> Resolution<S>, >; fn poll_ready(&mut self) -> Poll<(), Self::Error> { self.service.poll_ready() } fn call(&mut self, target: T) -> Self::Future { let path = target.to_string(); trace!("resolve {:?}", path); self.service .get(grpc::Request::new(api::GetDestination { path, scheme: self.scheme.clone(), context_token: self.context_token.clone(), })) .map(|rsp| { debug!(metadata = ?rsp.metadata()); Resolution { inner: rsp.into_inner(), } }) } } impl<S> resolve::Resolution for Resolution<S> where S: GrpcService<BoxBody>, { type Endpoint = Metadata; type Error = grpc::Status; fn poll(&mut self) -> Poll<Update<Self::Endpoint>, Self::Error> { loop { match try_ready!(self.inner.poll()) { Some(api::Update { update }) => match update { Some(api::update::Update::Add(api::WeightedAddrSet { addrs, metric_labels, })) => { let addr_metas = addrs .into_iter() .filter_map(|addr| pb::to_addr_meta(addr, &metric_labels)) .collect::<Vec<_>>(); if !addr_metas.is_empty() { return Ok(Update::Add(addr_metas).into()); } } Some(api::update::Update::Remove(api::AddrSet { addrs })) => { let sock_addrs = addrs .into_iter() .filter_map(pb::to_sock_addr) .collect::<Vec<_>>(); if !sock_addrs.is_empty() { return Ok(Update::Remove(sock_addrs).into()); } } Some(api::update::Update::NoEndpoints(api::NoEndpoints { exists })) => { let update = if exists { Update::Empty } else { Update::DoesNotExist }; return Ok(update.int
}
o()); } None => {} }, None => return Err(grpc::Status::new(grpc::Code::Ok, "end of stream")), }; } }
function_block-function_prefixed
[ { "content": "pub fn layer() -> map_target::Layer<impl Fn(Endpoint) -> Endpoint + Copy> {\n\n map_target::layer(|mut ep: Endpoint| {\n\n debug!(\"rewriting inbound address to loopback; addr={:?}\", ep.addr);\n\n ep.addr = SocketAddr::from(([127, 0, 0, 1], ep.addr.port()));\n\n ep\n\n ...
Rust
src/value.rs
basiliqio/messy_json
aa4f6dfbb5bb2a40ee03e7c1cac0b22c4893db59
use super::*; use serde_json::Value; use std::convert::From; use std::ops::Deref; #[derive(Clone, Debug, Eq, PartialEq, Default)] pub struct MessyJsonObjectValue<'a>(BTreeMap<ArcStr, MessyJsonValue<'a>>); #[derive(Clone, Debug, Eq, PartialEq)] pub enum MessyJsonNullType { Null, Absent, } impl<'a> Deref for MessyJsonObjectValue<'a> { type Target = BTreeMap<ArcStr, MessyJsonValue<'a>>; fn deref(&self) -> &Self::Target { &self.0 } } impl<'a> MessyJsonObjectValue<'a> { pub fn take(self) -> BTreeMap<ArcStr, MessyJsonValue<'a>> { self.0 } } impl<'a> From<BTreeMap<ArcStr, MessyJsonValue<'a>>> for MessyJsonObjectValue<'a> { fn from(obj: BTreeMap<ArcStr, MessyJsonValue<'a>>) -> Self { MessyJsonObjectValue(obj) } } impl<'a> From<Vec<MessyJsonValue<'a>>> for MessyJsonArrayValue<'a> { fn from(arr: Vec<MessyJsonValue<'a>>) -> Self { MessyJsonArrayValue(arr) } } impl<'a> MessyJsonArrayValue<'a> { pub fn take(self) -> Vec<MessyJsonValue<'a>> { self.0 } } #[derive(Clone, Debug, Eq, PartialEq)] pub struct MessyJsonArrayValue<'a>(Vec<MessyJsonValue<'a>>); impl<'a> Deref for MessyJsonArrayValue<'a> { type Target = Vec<MessyJsonValue<'a>>; fn deref(&self) -> &Self::Target { &self.0 } } #[derive(Clone, Debug, PartialEq, Eq)] pub enum MessyJsonValue<'a> { Array(MessyJsonArrayValue<'a>), Bool(bool), Number(u128), Obj(MessyJsonObjectValue<'a>), String(Cow<'a, str>), #[cfg(feature = "uuid")] Uuid(Cow<'a, feat_uuid::Uuid>), Null(MessyJsonNullType, MessyJsonExpected), } impl<'a> PartialEq<Value> for MessyJsonObjectValue<'a> { fn eq(&self, other: &Value) -> bool { match other { Value::Object(v_obj) => { for (k, v) in self.iter() { if let Some(x) = v_obj.get(k.as_str()) { if v != x { return false; } continue; } return false; } true } _ => false, } } } impl<'a> PartialEq<Value> for MessyJsonArrayValue<'a> { fn eq(&self, other: &Value) -> bool { match other { Value::Array(v_arr) => self.0.eq(v_arr), _ => false, } } } #[cfg(feature = "uuid")] impl<'a> PartialEq<feat_uuid::Uuid> for MessyJsonValue<'a> { fn eq(&self, other: &feat_uuid::Uuid) -> bool { match self { MessyJsonValue::Uuid(v_uuid) => *v_uuid == Cow::Borrowed(other), _ => false, } } } impl<'a> PartialEq<Value> for MessyJsonValue<'a> { fn eq(&self, other: &Value) -> bool { match (self, other) { (MessyJsonValue::Array(mj_arr), Value::Array(_)) => mj_arr.eq(other), (MessyJsonValue::Bool(mj_bool), Value::Bool(v_bool)) => mj_bool == v_bool, (MessyJsonValue::Number(mj_number), Value::Number(v_number)) => { let num = match v_number.as_u64() { Some(x) => x, None => return false, }; mj_number == &(num as u128) } (MessyJsonValue::Obj(mj_obj), Value::Object(_)) => mj_obj.eq(other), (MessyJsonValue::String(mj_str), Value::String(v_str)) => mj_str == v_str, (MessyJsonValue::Null(_, _), Value::Null) => true, _ => false, } } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct MessyJsonValueContainer<'a> { val: MessyJsonValue<'a>, } impl<'a> std::ops::Deref for MessyJsonValueContainer<'a> { type Target = MessyJsonValue<'a>; #[inline] fn deref(&self) -> &Self::Target { self.inner() } } impl<'a> MessyJsonValueContainer<'a> { #[inline] pub fn new(val: MessyJsonValue<'a>) -> Self { MessyJsonValueContainer { val } } #[inline] pub fn inner(&self) -> &MessyJsonValue<'a> { &self.val } #[inline] pub fn take(self) -> MessyJsonValue<'a> { self.val } }
use super::*; use serde_json::Value; use std::convert::From; use std::ops::Deref; #[derive(Clone, Debug, Eq, PartialEq, Default)] pub struct MessyJsonObjectValue<'a>(BTreeMap<ArcStr, MessyJsonValue<'a>>); #[derive(Clone, Debug, Eq, PartialEq)] pub enum MessyJsonNullType { Null, Absent, } impl<'a> Deref for MessyJsonObjectValue<'a> { type Target = BTreeMap<ArcStr, MessyJsonValue<'a>>; fn deref(&self) -> &Self::Target { &self.0 } } impl<'a> MessyJsonObjectValue<'a> { pub fn take(self) -> BTreeMap<ArcStr, MessyJsonValue<'a>> { self.0 } } impl<'a> From<BTreeMap<ArcStr, MessyJsonValue<'a>>> for MessyJsonObjectValue<'a> { fn from(obj: BTreeMap<ArcStr, MessyJsonValue<'a>>) -> Self { MessyJsonObjectValue(obj) } } impl<'a> From<Vec<MessyJsonValue<'a>>> for MessyJsonArrayValue<'a> { fn from(arr: Vec<MessyJsonValue<'a>>) -> Self { MessyJsonArrayValue(arr) } } impl<'a> MessyJ
), Value::Object(_)) => mj_obj.eq(other), (MessyJsonValue::String(mj_str), Value::String(v_str)) => mj_str == v_str, (MessyJsonValue::Null(_, _), Value::Null) => true, _ => false, } } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct MessyJsonValueContainer<'a> { val: MessyJsonValue<'a>, } impl<'a> std::ops::Deref for MessyJsonValueContainer<'a> { type Target = MessyJsonValue<'a>; #[inline] fn deref(&self) -> &Self::Target { self.inner() } } impl<'a> MessyJsonValueContainer<'a> { #[inline] pub fn new(val: MessyJsonValue<'a>) -> Self { MessyJsonValueContainer { val } } #[inline] pub fn inner(&self) -> &MessyJsonValue<'a> { &self.val } #[inline] pub fn take(self) -> MessyJsonValue<'a> { self.val } }
sonArrayValue<'a> { pub fn take(self) -> Vec<MessyJsonValue<'a>> { self.0 } } #[derive(Clone, Debug, Eq, PartialEq)] pub struct MessyJsonArrayValue<'a>(Vec<MessyJsonValue<'a>>); impl<'a> Deref for MessyJsonArrayValue<'a> { type Target = Vec<MessyJsonValue<'a>>; fn deref(&self) -> &Self::Target { &self.0 } } #[derive(Clone, Debug, PartialEq, Eq)] pub enum MessyJsonValue<'a> { Array(MessyJsonArrayValue<'a>), Bool(bool), Number(u128), Obj(MessyJsonObjectValue<'a>), String(Cow<'a, str>), #[cfg(feature = "uuid")] Uuid(Cow<'a, feat_uuid::Uuid>), Null(MessyJsonNullType, MessyJsonExpected), } impl<'a> PartialEq<Value> for MessyJsonObjectValue<'a> { fn eq(&self, other: &Value) -> bool { match other { Value::Object(v_obj) => { for (k, v) in self.iter() { if let Some(x) = v_obj.get(k.as_str()) { if v != x { return false; } continue; } return false; } true } _ => false, } } } impl<'a> PartialEq<Value> for MessyJsonArrayValue<'a> { fn eq(&self, other: &Value) -> bool { match other { Value::Array(v_arr) => self.0.eq(v_arr), _ => false, } } } #[cfg(feature = "uuid")] impl<'a> PartialEq<feat_uuid::Uuid> for MessyJsonValue<'a> { fn eq(&self, other: &feat_uuid::Uuid) -> bool { match self { MessyJsonValue::Uuid(v_uuid) => *v_uuid == Cow::Borrowed(other), _ => false, } } } impl<'a> PartialEq<Value> for MessyJsonValue<'a> { fn eq(&self, other: &Value) -> bool { match (self, other) { (MessyJsonValue::Array(mj_arr), Value::Array(_)) => mj_arr.eq(other), (MessyJsonValue::Bool(mj_bool), Value::Bool(v_bool)) => mj_bool == v_bool, (MessyJsonValue::Number(mj_number), Value::Number(v_number)) => { let num = match v_number.as_u64() { Some(x) => x, None => return false, }; mj_number == &(num as u128) } (MessyJsonValue::Obj(mj_obj
random
[ { "content": "#[cfg(test)]\n\npub fn gen_key(k: &str) -> super::object::KeyType {\n\n ArcStr::from(k)\n\n}\n", "file_path": "src/object.rs", "rank": 0, "score": 154589.97172367276 }, { "content": "#[test]\n\nfn null() {\n\n let nested_string = MessyJson::from(MessyJsonInner::String(Mes...
Rust
src/segment/data.rs
iFaceless/tinkv
b7f526ccfea53e82285891929bae177698947658
use crate::error::{Result, TinkvError}; use crate::util::{checksum, parse_file_id, BufReaderWithOffset, FileWithBufWriter}; use serde::{Deserialize, Serialize}; use log::{error, trace}; use std::fmt; use std::fs::{self, File}; use std::io::{copy, Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; #[derive(Serialize, Deserialize, Debug)] struct InnerEntry { key: Vec<u8>, value: Vec<u8>, checksum: u32, } impl InnerEntry { fn new(key: &[u8], value: &[u8]) -> Self { let mut ent = InnerEntry { key: key.into(), value: value.into(), checksum: 0, }; ent.checksum = ent.fresh_checksum(); ent } fn fresh_checksum(&self) -> u32 { checksum(&self.value) } fn is_valid(&self) -> bool { self.checksum == self.fresh_checksum() } } impl fmt::Display for InnerEntry { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "DataInnerEntry(key='{}', checksum={})", String::from_utf8_lossy(self.key.as_ref()), self.checksum, ) } } #[derive(Debug)] pub(crate) struct Entry { inner: InnerEntry, pub size: u64, pub offset: u64, pub file_id: u64, } impl Entry { fn new(file_id: u64, inner: InnerEntry, size: u64, offset: u64) -> Self { Self { inner, size, offset, file_id, } } pub(crate) fn is_valid(&self) -> bool { self.inner.is_valid() } pub(crate) fn key(&self) -> &[u8] { &self.inner.key } pub(crate) fn value(&self) -> &[u8] { &self.inner.value } } impl fmt::Display for Entry { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "DataEntry(file_id={}, key='{}', offset={}, size={})", self.file_id, String::from_utf8_lossy(self.key().as_ref()), self.offset, self.size, ) } } #[derive(Debug)] pub(crate) struct DataFile { pub path: PathBuf, pub id: u64, writeable: bool, writer: Option<FileWithBufWriter>, reader: BufReaderWithOffset<File>, pub size: u64, } impl DataFile { pub(crate) fn new(path: &Path, writeable: bool) -> Result<Self> { let file_id = parse_file_id(path).expect("file id not found in file path"); let w = if writeable { let f = fs::OpenOptions::new() .create(true) .write(true) .append(true) .open(path)?; Some(FileWithBufWriter::from(f)?) } else { None }; let file = fs::File::open(path)?; let size = file.metadata()?.len(); let df = DataFile { path: path.to_path_buf(), id: file_id, writeable, reader: BufReaderWithOffset::new(file)?, writer: w, size, }; Ok(df) } pub(crate) fn write(&mut self, key: &[u8], value: &[u8]) -> Result<Entry> { let inner = InnerEntry::new(key, value); trace!("append {} to segement file {}", &inner, self.path.display()); let path = self.path.as_path(); let encoded = bincode::serialize(&inner)?; let w = self .writer .as_mut() .ok_or_else(|| TinkvError::FileNotWriteable(path.to_path_buf()))?; let offset = w.offset(); w.write_all(&encoded)?; w.flush()?; self.size = offset + encoded.len() as u64; let entry = Entry::new(self.id, inner, encoded.len() as u64, offset); trace!( "successfully append {} to data file {}", &entry, self.path.display() ); Ok(entry) } pub(crate) fn read(&mut self, offset: u64) -> Result<Entry> { trace!( "read key value with offset {} in data file {}", offset, self.path.display() ); let reader = &mut self.reader; reader.seek(SeekFrom::Start(offset))?; let inner: InnerEntry = bincode::deserialize_from(reader)?; let entry = Entry::new(self.id, inner, self.reader.offset() - offset, offset); trace!( "successfully read {} from data log file {}", &entry, self.path.display() ); Ok(entry) } pub(crate) fn copy_bytes_from( &mut self, src: &mut DataFile, offset: u64, size: u64, ) -> Result<u64> { let reader = &mut src.reader; if reader.offset() != offset { reader.seek(SeekFrom::Start(offset))?; } let mut r = reader.take(size); let w = self.writer.as_mut().expect("data file is not writeable"); let offset = w.offset(); let num_bytes = copy(&mut r, w)?; assert_eq!(num_bytes, size); self.size += num_bytes; Ok(offset) } pub(crate) fn entry_iter(&self) -> EntryIter { EntryIter { path: self.path.clone(), reader: fs::File::open(self.path.clone()).unwrap(), file_id: self.id, } } pub(crate) fn sync(&mut self) -> Result<()> { self.flush()?; if self.writer.is_some() { self.writer.as_mut().unwrap().sync()?; } Ok(()) } fn flush(&mut self) -> Result<()> { if self.writeable { self.writer.as_mut().unwrap().flush()?; } Ok(()) } } impl Drop for DataFile { fn drop(&mut self) { if let Err(e) = self.sync() { error!( "failed to sync data file: {}, got error: {}", self.path.display(), e ); } if self.writeable && self.size == 0 && fs::remove_file(self.path.as_path()).is_ok() { trace!("data file '{}' is empty, remove it.", self.path.display()); } } } #[derive(Debug)] pub(crate) struct EntryIter { path: PathBuf, reader: fs::File, file_id: u64, } impl Iterator for EntryIter { type Item = Entry; fn next(&mut self) -> Option<Self::Item> { let offset = self.reader.seek(SeekFrom::Current(0)).unwrap(); let inner: InnerEntry = bincode::deserialize_from(&self.reader).ok()?; let new_offset = self.reader.seek(SeekFrom::Current(0)).unwrap(); let entry = Entry::new(self.file_id, inner, new_offset - offset, offset); trace!( "iter read {} from data file {}", &entry, self.path.display() ); Some(entry) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_new_entry() { let ent = InnerEntry::new(&b"key".to_vec(), &b"value".to_vec()); assert_eq!(ent.checksum, 494360628); } #[test] fn test_checksum_valid() { let ent = InnerEntry::new(&b"key".to_vec(), &b"value".to_vec()); assert_eq!(ent.is_valid(), true); } #[test] fn test_checksum_invalid() { let mut ent = InnerEntry::new(&b"key".to_vec(), &b"value".to_vec()); ent.value = b"value_changed".to_vec(); assert_eq!(ent.is_valid(), false); } }
use crate::error::{Result, TinkvError}; use crate::util::{checksum, parse_file_id, BufReaderWithOffset, FileWithBufWriter}; use serde::{Deserialize, Serialize}; use log::{error, trace}; use std::fmt; use std::fs::{self, File}; use std::io::{copy, Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; #[derive(Serialize, Deserialize, Debug)] struct InnerEntry { key: Vec<u8>, value: Vec<u8>, checksum: u32, } impl InnerEntry { fn new(key: &[u8], value: &[u8]) -> Self { let mut ent = InnerEntry { key: key.into(), value: value.into(), checksum: 0, }; ent.checksum = ent.fresh_checksum(); ent } fn fresh_checksum(&self) -> u32 { checksum(&self.value) } fn is_valid(&self) -> bool { self.checksum == self.fresh_checksum() } } impl fmt::Display for InnerEntry { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "DataInnerEntry(key='{}', checksum={})", String::from_utf8_lossy(self.key.as_ref()), self.checksum, ) } } #[derive(Debug)] pub(crate) struct Entry { inner: InnerEntry, pub size: u64, pub offset: u64, pub file_id: u64, } impl Entry { fn new(file_id: u64, inner: InnerEntry, size: u64, offset: u64) -> Self { Self { inner, size, offset, file_id, } } pub(crate) fn is_valid(&self) -> bool { self.inner.is_valid() } pub(crate) fn key(&self) -> &[u8] { &self.inner.key } pub(crate) fn value(&self) -> &[u8] { &self.inner.value } } impl fmt::Display for Entry { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "DataEntry(file_id={}, key='{}', offset={}, size={})", self.file_id, String::from_utf8_lossy(self.key().as_ref()), self.offset, self.size, ) } } #[derive(Debug)] pub(crate) struct DataFile { pub path: PathBuf, pub id: u64, writeable: bool, writer: Option<FileWithBufWriter>, reader: BufReaderWithOffset<File>, pub size: u64, } impl DataFile { pub(crate) fn new(path: &Path, writeable: bool) -> Result<Self> { let file_id = parse_file_id(path).expect("file id not found in file path"); let w = if writeable { let f = fs::OpenOptions::new() .create(true) .write(true) .append(true) .open(path)?; Some(FileWithBufWriter::from(f)?) } else { None }; let file = fs::File::open(path)?; let size = file.metadata()?.len(); let df = DataFile { path: path.to_path_buf(), id: file_id, writeable, reader: BufReaderWithOffset::new(file)?, writer: w, size, }; Ok(df) } pub(crate) fn write(&mut self, key: &[u8], value: &[u8]) -> Result<Entry> { let inner = InnerEntry::new(key, value); trace!("append {} to segement file {}", &inner, self.path.display()); let path = self.path.as_path(); let encoded = bincode::serialize(&inner)?; let w = self .writer .as_mut() .ok_or_else(|| TinkvError::FileNotWriteable(path.to_path_buf()))?; let offset = w.offset(); w.write_all(&encoded)?; w.flush()?; self.size = offset + encoded.len() as u64; let entry = Entry::new(self.id, inner, encoded.len() as u64, offset); trace!( "successfully append {} to data file {}", &entry, self.path.display() ); Ok(entry) } pub(crate) fn read(&mut self, offset: u64) -> Result<Entry> { trace!( "read key value with offset {} in data file {}", offset, self.path.display() ); let reader = &mut self.reader; reader.seek(SeekFrom::Start(offset))?; let inner: InnerEntry = bincode::deserialize_from(reader)?; let entry = Entry::new(self.id, inner, self.reader.offset() - offset, offset); trace!( "successfully read {} from data log file {}", &entry, self.path.display() ); Ok(entry) } pub(crate) fn copy_bytes_from( &mut self, src: &mut DataFile, offset: u64, size: u64, ) -> Result<u64> { let reader = &mut src.reader; if reader.offset() != offset { reader.seek(SeekFrom::Start(offset))?; } let mut r = reader.take(size); let w = self.writer.as_mut().expect("data file is not writeable"); let offset = w.offset(); let num_bytes = copy(&mut r, w)?; assert_eq!(num_bytes, size); self.size += num_bytes; Ok(offset) } pub(crate) fn entry_iter(&self) -> EntryIter { EntryIter { path: self.path.clone(), reader: fs::File::open(self.path.clone()).unwrap(), file_id: self.id, } } pub(crate) fn sync(&mut self) -> Result<()> { self.flush()?; if self.writer.is_some() { self.writer.as_mut().unwrap().sync()?; } Ok(()) } fn flush(&mut self) -> Result<()> { if self.writeable { self.writer.as_mut().unwrap().flush()?; } Ok(()) } } impl Drop for DataFile { fn drop(&mut self) { if let Err(e) = self.sync() { error!( "failed to sync data file: {}, got error: {}", self.path.display(), e ); } if self.writeable && self.size == 0 && fs::remove_file(self.path.as_path()).is_ok() { trace!("data file '{}' is empty, remove it.", self.path.display()); } } } #[derive(Debug)] pub(crate) struct EntryIter { path: PathBuf, reader: fs::File, file_id: u64, } impl Iterator for EntryIter { type Item = Entry;
} #[cfg(test)] mod tests { use super::*; #[test] fn test_new_entry() { let ent = InnerEntry::new(&b"key".to_vec(), &b"value".to_vec()); assert_eq!(ent.checksum, 494360628); } #[test] fn test_checksum_valid() { let ent = InnerEntry::new(&b"key".to_vec(), &b"value".to_vec()); assert_eq!(ent.is_valid(), true); } #[test] fn test_checksum_invalid() { let mut ent = InnerEntry::new(&b"key".to_vec(), &b"value".to_vec()); ent.value = b"value_changed".to_vec(); assert_eq!(ent.is_valid(), false); } }
fn next(&mut self) -> Option<Self::Item> { let offset = self.reader.seek(SeekFrom::Current(0)).unwrap(); let inner: InnerEntry = bincode::deserialize_from(&self.reader).ok()?; let new_offset = self.reader.seek(SeekFrom::Current(0)).unwrap(); let entry = Entry::new(self.file_id, inner, new_offset - offset, offset); trace!( "iter read {} from data file {}", &entry, self.path.display() ); Some(entry) }
function_block-full_function
[ { "content": "pub fn checksum(data: &[u8]) -> u32 {\n\n crc::crc32::checksum_ieee(data)\n\n}\n\n\n", "file_path": "src/util/misc.rs", "rank": 0, "score": 211904.36433031445 }, { "content": "pub fn parse_file_id(path: &Path) -> Option<u64> {\n\n path.file_name()?\n\n .to_str()?\n...
Rust
artichoke-backend/src/extn/core/random/mruby.rs
Talljoe/artichoke
36ed5eba078a9fbf3cb4d5c8f7407d0a773d2d6e
use crate::extn::core::random::{self, trampoline}; use crate::extn::prelude::*; pub fn init(interp: &mut Artichoke) -> InitializeResult<()> { if interp.is_class_defined::<random::Random>() { return Ok(()); } let spec = class::Spec::new("Random", None, Some(def::box_unbox_free::<random::Random>))?; class::Builder::for_spec(interp, &spec) .value_is_rust_object() .add_self_method( "new_seed", artichoke_random_self_new_seed, sys::mrb_args_req(1), )? .add_self_method("srand", artichoke_random_self_srand, sys::mrb_args_opt(1))? .add_self_method( "urandom", artichoke_random_self_urandom, sys::mrb_args_req(1), )? .add_method( "initialize", artichoke_random_initialize, sys::mrb_args_opt(1), )? .add_method("==", artichoke_random_eq, sys::mrb_args_opt(1))? .add_method("bytes", artichoke_random_bytes, sys::mrb_args_req(1))? .add_method("rand", artichoke_random_rand, sys::mrb_args_opt(1))? .add_method("seed", artichoke_random_seed, sys::mrb_args_none())? .define()?; interp.def_class::<random::Random>(spec)?; let default = random::Random::interpreter_prng_delegate(); let default = random::Random::alloc_value(default, interp) .map_err(|_| NotDefinedError::class_constant("Random::DEFAULT"))?; interp.define_class_constant::<random::Random>("DEFAULT", default)?; let _ = interp.eval(&include_bytes!("random.rb")[..])?; trace!("Patched Random onto interpreter"); Ok(()) } #[no_mangle] unsafe extern "C" fn artichoke_random_initialize( mrb: *mut sys::mrb_state, slf: sys::mrb_value, ) -> sys::mrb_value { let seed = mrb_get_args!(mrb, optional = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let slf = Value::from(slf); let seed = seed.map(Value::from); let result = trampoline::initialize(&mut guard, seed, slf); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } } #[no_mangle] unsafe extern "C" fn artichoke_random_eq( mrb: *mut sys::mrb_state, slf: sys::mrb_value, ) -> sys::mrb_value { let other = mrb_get_args!(mrb, required = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let rand = Value::from(slf); let other = Value::from(other); let result = trampoline::equal(&mut guard, rand, other); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } } #[no_mangle] unsafe extern "C" fn artichoke_random_bytes( mrb: *mut sys::mrb_state, slf: sys::mrb_value, ) -> sys::mrb_value { let size = mrb_get_args!(mrb, required = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let rand = Value::from(slf); let size = Value::from(size); let result = trampoline::bytes(&mut guard, rand, size); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } } #[no_mangle] unsafe extern "C" fn artichoke_random_rand( mrb: *mut sys::mrb_state, slf: sys::mrb_value, ) -> sys::mrb_value { let max = mrb_get_args!(mrb, optional = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let rand = Value::from(slf); let max = max.map(Value::from); let result = trampoline::rand(&mut guard, rand, max); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } } #[no_mangle] unsafe extern "C" fn artichoke_random_seed( mrb: *mut sys::mrb_state, slf: sys::mrb_value, ) -> sys::mrb_value { mrb_get_args!(mrb, none); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let rand = Value::from(slf); let result = trampoline::seed(&mut guard, rand); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } } #[no_mangle] unsafe extern "C" fn artichoke_random_self_new_seed( mrb: *mut sys::mrb_state, _slf: sys::mrb_value, ) -> sys::mrb_value { mrb_get_args!(mrb, none); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let result = trampoline::new_seed(&mut guard); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } } #[no_mangle] unsafe extern "C" fn artichoke_random_self_srand( mrb: *mut sys::mrb_state, _slf: sys::mrb_value, ) -> sys::mrb_value { let number = mrb_get_args!(mrb, optional = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let number = number.map(Value::from); let result = trampoline::srand(&mut guard, number); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } } #[no_mangle] unsafe extern "C" fn artichoke_random_self_urandom( mrb: *mut sys::mrb_state, _slf: sys::mrb_value, ) -> sys::mrb_value { let size = mrb_get_args!(mrb, required = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let size = Value::from(size); let result = trampoline::urandom(&mut guard, size); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } }
use crate::extn::core::random::{self, trampoline}; use crate::extn::prelude::*; pub fn init(interp: &mut Artichoke) -> InitializeResult<()> { if interp.is_class_defined::<random::Random>() { return Ok(()); } let spec = class::Spec::new("Random", None, Some(def::box_unbox_free::<random::Random>))?; class::Builder::for_spec(interp, &spec) .value_is_rust_object() .add_self_method( "new_seed", artichoke_random_self_new_seed, sys::mrb_args_req(1), )? .add_self_method("srand", artichoke_random_self_srand, sys::mrb_args_opt(1))? .add_self_method( "urandom", artichoke_random_self_urandom, sys::mrb_args_req(1), )? .add_method( "initialize", artichoke_random_initialize, sys::mrb_args_opt(1), )? .add_method("==", artichoke_random_eq, sys::mrb_args_opt(1))? .add_method("bytes", artichoke_random_bytes, sys::mrb_args_req(1))? .add_method("rand", artichoke_random_rand, sys::mrb_args_opt(1))? .add_method("seed", artichoke_random_seed, sys::mrb_args_none())? .define()?; interp.def_class::<random::Random>(spec)?; let default = random::Random::interpreter_prng_delegate(); let default = random::Random::alloc_value(default, interp) .map_err(|_| NotDefinedError::class_constant("Random::DEFAULT"))?; interp.define_class_constant::<random::Random>("DEFAULT", default)?; let _ = interp.eval(&include_bytes!("random.rb")[..])?; trace!("Patched Random onto interpreter"); Ok(()) } #[no_mangle] unsafe extern "C" fn artichoke_random_initialize( mrb: *mut sys::mrb_state, slf: sys::mrb_value, ) -> sys::mrb_value { let seed = mrb_get_args!(mrb, optional = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let slf = Value::from(slf); let seed = seed.map(Value::from); let result = trampoline::initialize(&mut guard, seed, slf); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } } #[no_mangle] unsafe extern "C" fn artichoke_random_eq( mrb: *mut sys::mrb_state, slf: sys::mrb_value, ) -> sys::mrb_value { let other = mrb_get_args!(mrb, required = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let rand = Value::from(slf); let other = Value::from(other); let result = trampoline::equal(&mut guard, rand, other); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } } #[no_mangle] unsafe extern "C" fn artichoke_random_bytes( mrb: *mut sys::mrb_state, slf: sys::mrb_value, ) -> sys::mrb_value { let size = mrb_get_args!(mrb, required = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let rand = Value::from(slf); let size = Value::from(size); let result = trampoline::bytes(&mut guard, rand, size); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } } #[no_mangle] unsafe extern "C" fn artichoke_random_rand( mrb: *mut sys::mrb_state, slf: sys::mrb_value, ) -> sys::mrb_value { let max = mrb_get_args!(mrb, optional = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let rand = Value::from(slf); let max = max.map(Value::from); let result = trampoline::rand(&mut guard, rand, max); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } } #[no_mangle] unsafe extern "C" fn artichoke_random_seed( mrb: *mut sys::mrb_state, slf: sys::mrb_value, ) -> sys::mrb_value { mrb_get_args!(mrb, none); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let rand = Value::from(slf); let result = trampoline::seed(&mut guard, rand); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } } #[no_mangle] unsafe extern "C" fn artichoke_random_self_new_seed( mrb: *mut sys::mrb_state, _slf: sys::mrb_value, ) -> sys::mrb_value { mrb_get_args!(mrb, none); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let result = trampoline::new_seed(&mut guard); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } } #[no_mangle]
#[no_mangle] unsafe extern "C" fn artichoke_random_self_urandom( mrb: *mut sys::mrb_state, _slf: sys::mrb_value, ) -> sys::mrb_value { let size = mrb_get_args!(mrb, required = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let size = Value::from(size); let result = trampoline::urandom(&mut guard, size); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } }
unsafe extern "C" fn artichoke_random_self_srand( mrb: *mut sys::mrb_state, _slf: sys::mrb_value, ) -> sys::mrb_value { let number = mrb_get_args!(mrb, optional = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let number = number.map(Value::from); let result = trampoline::srand(&mut guard, number); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } }
function_block-full_function
[ { "content": "pub fn seed(interp: &mut Artichoke, mut rand: Value) -> Result<Value, Exception> {\n\n let rand = unsafe { Random::unbox_from_value(&mut rand, interp)? };\n\n let seed = rand.seed(interp)?;\n\n Ok(interp.convert(seed))\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/random/...
Rust
src/init.rs
dandyvica/clf
0774f971a973d89688a72f7283e251c7a429e946
use std::fs::OpenOptions; use std::path::PathBuf; use simplelog::*; use crate::configuration::{config::Config, script::Script}; use crate::logfile::snapshot::Snapshot; use crate::misc::extension::Expect; use crate::misc::nagios::Nagios; use crate::{args::CliOptions, configuration::vars::GlobalVars}; pub fn init_config(options: &CliOptions) -> Config { #[cfg(feature = "tera")] let _config = Config::from_path( &options.config_file, options.tera_context.as_deref(), options.show_rendered, ); #[cfg(not(feature = "tera"))] let _config = Config::from_path(&options.config_file); if let Err(ref e) = _config { Nagios::exit_critical(&format!( "error loading config file: {:?}, error: {}", &options.config_file, e )); } let mut config = _config.unwrap(); config.global.insert_process_vars(&options.config_file); config.global.insert_extra_vars(&options.extra_vars); let all_vars: Vec<_> = config .global .global_vars .iter() .map(|(k, v)| format!("{}='{}'", k, v)) .collect(); info!("global variables: {}", all_vars.join(" ")); config } pub fn init_log(options: &CliOptions) { let logger = &options.clf_logger; let writable = if options.reset_log { OpenOptions::new() .write(true) .truncate(true) .create(true) .open(logger) } else { OpenOptions::new().append(true).create(true).open(logger) }; if let Err(ref e) = writable { Nagios::exit_critical(&format!( "unable to open or create log file {:?}, error {}", logger, e )); } match WriteLogger::init( options.logger_level, simplelog::ConfigBuilder::new() .set_time_format("%Y-%b-%d %H:%M:%S.%f".to_string()) .build(), writable.unwrap(), ) { Ok(_) => (), Err(e) => { Nagios::exit_critical(&format!( "unable to create log file: {}, error: {}", logger.display(), e )); } }; let metadata = std::fs::metadata(&logger) .expect_critical(&format!("error on metadata() API, path {:?}", &logger)); debug!("current logger size is: {} bytes", metadata.len()); if metadata.len() > options.max_logger_size { if let Err(e) = std::fs::remove_file(&logger) { if e.kind() != std::io::ErrorKind::NotFound { error!("unable to delete logger file: {:?}, error: {}", &logger, e); } } else { info!("deleting logger file {:?}", &logger); } } info!( "=============================> using configuration file: {:?}", &options.config_file ); info!("options: {:?}", &options); } pub fn load_snapshot( options: &CliOptions, config_snapshot_file: &Option<PathBuf>, ) -> (Snapshot, PathBuf) { let snapfile = if options.snapshot_file.is_some() { options.snapshot_file.as_ref().unwrap().clone() } else if config_snapshot_file.is_some() { let conf_file_or_dir = config_snapshot_file.as_ref().unwrap(); if conf_file_or_dir.is_dir() { Snapshot::build_name(&options.config_file, Some(conf_file_or_dir)) } else { conf_file_or_dir.clone() } } else { Snapshot::build_name(&options.config_file, None) }; if options.delete_snapfile { if let Err(e) = std::fs::remove_file(&snapfile) { if e.kind() != std::io::ErrorKind::NotFound { error!( "unable to delete snapshot file: {:?}, error: {}", &snapfile, e ); } } else { info!("deleting snapshot file {:?}", &snapfile); } } info!("using snapshot file:{}", &snapfile.display()); let snapshot = Snapshot::load(&snapfile) .expect_critical(&format!("unable to load snapshot file: {:?},", &snapfile)); info!( "loaded snapshot file {:?}, data = {:#?}", &snapfile, &snapshot ); (snapshot, snapfile) } pub fn save_snapshot(snapshot: &mut Snapshot, snapfile: &PathBuf, retention: u64) { debug!("saving snapshot file {}", &snapfile.display()); if let Err(e) = snapshot.save(&snapfile, retention) { Nagios::exit_critical(&format!( "unable to save snapshot file: {:?}, error: {}", &snapfile, e )); } } pub fn spawn_prescript(prescript: &Script, vars: Option<&GlobalVars>) -> u32 { let result = prescript.spawn(vars); if let Err(e) = &result { error!("error: {} spawning prescript: {:?}", e, prescript.command); Nagios::exit_critical(&format!( "error: {} spawning prescript: {:?}", e, prescript.command )); } debug_assert!(result.is_ok()); result.unwrap() } pub fn spawn_postscript(postscript: &mut Script, pids: &[u32]) { for pid in pids { postscript.command.push(pid.to_string()); } trace!("postscript: {:?}", &postscript.command); let result = postscript.spawn(None); if let Err(e) = &result { error!("error: {} spawning command: {:?}", e, postscript.command); } else { info!( "postcript command successfully executed, pid={}", result.unwrap() ) } }
use std::fs::OpenOptions; use std::path::PathBuf; use simplelog::*; use crate::configuration::{config::Config, script::Script}; use crate::logfile::snapshot::Snapshot; use crate::misc::extension::Expect; use crate::misc::nagios::Nagios; use crate::{args::CliOptions, configuration::vars::GlobalVars}; pub fn init_config(options: &CliOptions) -> Config { #[cfg(feature = "tera")] let _config = Config::from_path( &options.config_file, options.tera_context.as_deref(), options.show_rendered, ); #[cfg(not(feature = "tera"))] let _config = Config::from_path(&options.config_file); if let Err(ref e) = _config { Nagios::exit_critical(&format!( "error loading config file: {:?}, error: {}", &options.config_file, e )); } let mut config = _config.unwrap(); config.global.insert_process_vars(&options.config_file); config.global.insert_extra_vars(&options.extra_vars); let all_vars: Vec<_> = config .global .global_vars .iter() .map(|(k, v)| format!("{}='{}'", k, v)) .collect(); info!("global variables: {}", all_vars.join(" ")); config } pub fn init_log(options: &CliOptions) { let logger = &options.clf_logger; let writable = if options.reset_log { OpenOptions::new() .write(true) .truncate(true) .create(true) .open(logger) } else { OpenOptions::new().append(true).create(true).open(logger) }; if let Err(ref e) = writable { Nagios::exit_critical(&format!( "unable to open or create log file {:?}, error {}", logger, e )); } match WriteLogger::init( options.logger_level, simplelog::ConfigBuilder::new() .set_time_format("%Y-%b-%d %H:%M:%S.%f".to_string()) .build(), writable.unwrap(), ) { Ok(_) => (),
ger size is: {} bytes", metadata.len()); if metadata.len() > options.max_logger_size { if let Err(e) = std::fs::remove_file(&logger) { if e.kind() != std::io::ErrorKind::NotFound { error!("unable to delete logger file: {:?}, error: {}", &logger, e); } } else { info!("deleting logger file {:?}", &logger); } } info!( "=============================> using configuration file: {:?}", &options.config_file ); info!("options: {:?}", &options); } pub fn load_snapshot( options: &CliOptions, config_snapshot_file: &Option<PathBuf>, ) -> (Snapshot, PathBuf) { let snapfile = if options.snapshot_file.is_some() { options.snapshot_file.as_ref().unwrap().clone() } else if config_snapshot_file.is_some() { let conf_file_or_dir = config_snapshot_file.as_ref().unwrap(); if conf_file_or_dir.is_dir() { Snapshot::build_name(&options.config_file, Some(conf_file_or_dir)) } else { conf_file_or_dir.clone() } } else { Snapshot::build_name(&options.config_file, None) }; if options.delete_snapfile { if let Err(e) = std::fs::remove_file(&snapfile) { if e.kind() != std::io::ErrorKind::NotFound { error!( "unable to delete snapshot file: {:?}, error: {}", &snapfile, e ); } } else { info!("deleting snapshot file {:?}", &snapfile); } } info!("using snapshot file:{}", &snapfile.display()); let snapshot = Snapshot::load(&snapfile) .expect_critical(&format!("unable to load snapshot file: {:?},", &snapfile)); info!( "loaded snapshot file {:?}, data = {:#?}", &snapfile, &snapshot ); (snapshot, snapfile) } pub fn save_snapshot(snapshot: &mut Snapshot, snapfile: &PathBuf, retention: u64) { debug!("saving snapshot file {}", &snapfile.display()); if let Err(e) = snapshot.save(&snapfile, retention) { Nagios::exit_critical(&format!( "unable to save snapshot file: {:?}, error: {}", &snapfile, e )); } } pub fn spawn_prescript(prescript: &Script, vars: Option<&GlobalVars>) -> u32 { let result = prescript.spawn(vars); if let Err(e) = &result { error!("error: {} spawning prescript: {:?}", e, prescript.command); Nagios::exit_critical(&format!( "error: {} spawning prescript: {:?}", e, prescript.command )); } debug_assert!(result.is_ok()); result.unwrap() } pub fn spawn_postscript(postscript: &mut Script, pids: &[u32]) { for pid in pids { postscript.command.push(pid.to_string()); } trace!("postscript: {:?}", &postscript.command); let result = postscript.spawn(None); if let Err(e) = &result { error!("error: {} spawning command: {:?}", e, postscript.command); } else { info!( "postcript command successfully executed, pid={}", result.unwrap() ) } }
Err(e) => { Nagios::exit_critical(&format!( "unable to create log file: {}, error: {}", logger.display(), e )); } }; let metadata = std::fs::metadata(&logger) .expect_critical(&format!("error on metadata() API, path {:?}", &logger)); debug!("current log
function_block-random_span
[ { "content": "/// Converts the error to string.\n\npub fn error_to_string<S>(value: &Option<AppError>, serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n if value.is_none() {\n\n \"None\".to_string().serialize(serializer)\n\n } else {\n\n format!(\"{}\", value....
Rust
src/test/spec/v2_runner/test_file.rs
dtolnay-contrib/mongo-rust-driver
1a096bd0d459c1bf6bc59a6a4dc930476043995f
use std::collections::HashMap; use bson::{doc, from_document}; use futures::TryStreamExt; use semver::VersionReq; use serde::{Deserialize, Deserializer}; use crate::{ bson::Document, options::{FindOptions, ReadPreference, SelectionCriteria, SessionOptions}, test::{spec::deserialize_uri_options_to_uri_string, EventClient, FailPoint, TestClient}, }; use super::{operation::Operation, test_event::CommandStartedEvent}; #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct TestFile { #[serde(rename = "runOn")] pub run_on: Option<Vec<RunOn>>, pub database_name: Option<String>, pub collection_name: Option<String>, pub bucket_name: Option<String>, pub data: Option<TestData>, pub tests: Vec<Test>, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RunOn { pub min_server_version: Option<String>, pub max_server_version: Option<String>, pub topology: Option<Vec<String>>, } impl RunOn { pub fn can_run_on(&self, client: &TestClient) -> bool { if let Some(ref min_version) = self.min_server_version { let req = VersionReq::parse(&format!(">= {}", &min_version)).unwrap(); if !req.matches(&client.server_version) { return false; } } if let Some(ref max_version) = self.max_server_version { let req = VersionReq::parse(&format!("<= {}", &max_version)).unwrap(); if !req.matches(&client.server_version) { return false; } } if let Some(ref topology) = self.topology { if !topology.contains(&client.topology_string()) { return false; } } true } } #[derive(Debug, Deserialize)] #[serde(untagged)] pub enum TestData { Single(Vec<Document>), Many(HashMap<String, Vec<Document>>), } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct Test { pub description: String, pub skip_reason: Option<String>, pub use_multiple_mongoses: Option<bool>, #[serde( default, deserialize_with = "deserialize_uri_options_to_uri_string_option", rename = "clientOptions" )] pub client_uri: Option<String>, pub fail_point: Option<FailPoint>, pub session_options: Option<HashMap<String, SessionOptions>>, pub operations: Vec<Operation>, #[serde(default, deserialize_with = "deserialize_command_started_events")] pub expectations: Option<Vec<CommandStartedEvent>>, pub outcome: Option<Outcome>, } fn deserialize_uri_options_to_uri_string_option<'de, D>( deserializer: D, ) -> std::result::Result<Option<String>, D::Error> where D: Deserializer<'de>, { Ok(Some(deserialize_uri_options_to_uri_string(deserializer)?)) } #[derive(Debug, Deserialize)] pub struct Outcome { pub collection: CollectionOutcome, } impl Outcome { pub async fn matches_actual( self, db_name: String, coll_name: String, client: &EventClient, ) -> bool { let coll_name = match self.collection.name { Some(name) => name, None => coll_name, }; let coll = client.database(&db_name).collection(&coll_name); let selection_criteria = SelectionCriteria::ReadPreference(ReadPreference::Primary); let options = FindOptions::builder() .sort(doc! { "_id": 1 }) .selection_criteria(selection_criteria) .build(); let actual_data: Vec<Document> = coll .find(None, options) .await .unwrap() .try_collect() .await .unwrap(); actual_data == self.collection.data } } #[derive(Debug, Deserialize)] pub struct CollectionOutcome { pub name: Option<String>, pub data: Vec<Document>, } fn deserialize_command_started_events<'de, D>( deserializer: D, ) -> std::result::Result<Option<Vec<CommandStartedEvent>>, D::Error> where D: Deserializer<'de>, { let docs = Vec::<Document>::deserialize(deserializer)?; Ok(Some( docs.iter() .map(|doc| { let event = doc.get_document("command_started_event").unwrap(); from_document(event.clone()).unwrap() }) .collect(), )) }
use std::collections::HashMap; use bson::{doc, from_document}; use futures::TryStreamExt; use semver::VersionReq; use serde::{Deserialize, Deserializer}; use crate::{ bson::Document, options::{FindOptions, ReadPreference, SelectionCriteria, SessionOptions}, test::{spec::deserialize_uri_options_to_uri_string, EventClient, FailPoint, TestClient}, }; use super::{operation::Operation, test_event::CommandStartedEvent}; #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct TestFile { #[serde(rename = "runOn")] pub run_on: Option<Vec<RunOn>>, pub database_name: Option<String>, pub collection_name: Option<String>, pub bucket_name: Option<String>, pub data: Option<TestData>, pub tests: Vec<Test>, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RunOn { pub min_server_version: Option<String>, pub max_server_version: Option<String>, pub topology: Option<Vec<String>>, } impl RunOn { pub
} #[derive(Debug, Deserialize)] #[serde(untagged)] pub enum TestData { Single(Vec<Document>), Many(HashMap<String, Vec<Document>>), } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct Test { pub description: String, pub skip_reason: Option<String>, pub use_multiple_mongoses: Option<bool>, #[serde( default, deserialize_with = "deserialize_uri_options_to_uri_string_option", rename = "clientOptions" )] pub client_uri: Option<String>, pub fail_point: Option<FailPoint>, pub session_options: Option<HashMap<String, SessionOptions>>, pub operations: Vec<Operation>, #[serde(default, deserialize_with = "deserialize_command_started_events")] pub expectations: Option<Vec<CommandStartedEvent>>, pub outcome: Option<Outcome>, } fn deserialize_uri_options_to_uri_string_option<'de, D>( deserializer: D, ) -> std::result::Result<Option<String>, D::Error> where D: Deserializer<'de>, { Ok(Some(deserialize_uri_options_to_uri_string(deserializer)?)) } #[derive(Debug, Deserialize)] pub struct Outcome { pub collection: CollectionOutcome, } impl Outcome { pub async fn matches_actual( self, db_name: String, coll_name: String, client: &EventClient, ) -> bool { let coll_name = match self.collection.name { Some(name) => name, None => coll_name, }; let coll = client.database(&db_name).collection(&coll_name); let selection_criteria = SelectionCriteria::ReadPreference(ReadPreference::Primary); let options = FindOptions::builder() .sort(doc! { "_id": 1 }) .selection_criteria(selection_criteria) .build(); let actual_data: Vec<Document> = coll .find(None, options) .await .unwrap() .try_collect() .await .unwrap(); actual_data == self.collection.data } } #[derive(Debug, Deserialize)] pub struct CollectionOutcome { pub name: Option<String>, pub data: Vec<Document>, } fn deserialize_command_started_events<'de, D>( deserializer: D, ) -> std::result::Result<Option<Vec<CommandStartedEvent>>, D::Error> where D: Deserializer<'de>, { let docs = Vec::<Document>::deserialize(deserializer)?; Ok(Some( docs.iter() .map(|doc| { let event = doc.get_document("command_started_event").unwrap(); from_document(event.clone()).unwrap() }) .collect(), )) }
fn can_run_on(&self, client: &TestClient) -> bool { if let Some(ref min_version) = self.min_server_version { let req = VersionReq::parse(&format!(">= {}", &min_version)).unwrap(); if !req.matches(&client.server_version) { return false; } } if let Some(ref max_version) = self.max_server_version { let req = VersionReq::parse(&format!("<= {}", &max_version)).unwrap(); if !req.matches(&client.server_version) { return false; } } if let Some(ref topology) = self.topology { if !topology.contains(&client.topology_string()) { return false; } } true }
function_block-function_prefixed
[ { "content": "#[derive(Debug, Deserialize)]\n\nstruct TestTopologyDescription {\n\n #[serde(rename = \"type\")]\n\n topology_type: TopologyType,\n\n servers: Vec<TestServerDescription>,\n\n}\n\n\n\nimpl TestTopologyDescription {\n\n fn into_topology_description(\n\n self,\n\n heartbeat...
Rust
src/io.rs
pajamapants3000/red
79292885d1dc6efe7ef98c27a9ec25622cfc12ac
/* * File : io.rs * Purpose: handles input/output functionality * Program: red * About : What does this program do? * Authors: Tommy Lincoln <pajamapants3000@gmail.com> * License: MIT; See LICENSE! * Notes : Notes on successful compilation * Created: 10/26/2016 */ use std::fs::{File, OpenOptions}; use std::path::Path; use std::process::{Command, Output}; use std::io::{self, BufRead, Write}; use std::ffi::OsStr; use regex::Regex; use error::*; use ::{EditorState, EditorMode}; const PROMPT_CONTINUE: &'static str = ">"; const PROMPT_INSERT: &'static str = "!"; #[derive(Default)] pub struct FileMode { pub f_write: bool, pub f_read: bool, pub f_append: bool, pub f_truncate: bool, pub f_create: bool, pub f_create_new: bool, } /* struct FileCoordinate { line: usize, col: usize, } */ /* /// Return next occurrence of regular expression regex_search( needle: &str, from: FileCoordinate ) -> FileCoordinate { } */ pub fn file_opener<S: AsRef<OsStr> + ?Sized>( name: &S, mode: FileMode ) -> Result<File, RedError> { OpenOptions::new() .read(mode.f_read) .write(mode.f_write) .append(mode.f_append) .truncate(mode.f_truncate) .create(mode.f_create) .create_new(mode.f_create_new) .open( Path::new(name) ).map_err(|err| RedError::FileOpen( err ) ) } pub fn get_input( mut input_buffer: String, state: &EditorState ) -> Result<String, RedError> { let stdin = io::stdin(); let stdout = io::stdout(); let mut stdin_handle = stdin.lock(); let mut stdout_handle = stdout.lock(); let mut prompt: &str; match state.mode { EditorMode::Command => prompt = &state.prompt, EditorMode::Insert => prompt = PROMPT_INSERT, } lazy_static! { static ref RE: Regex = Regex::new( r#".*\\"# ) .expect("get_input: failed to compile regex"); } loop { match input_buffer.pop() { Some(x) => { assert_eq!( x, '\\' ); input_buffer.push( '\n' ); }, None => {}, } try!( stdout_handle.write( prompt.as_bytes() ) .map_err( |_| RedError::Stdout )); try!( stdout_handle.flush().map_err( |_| RedError::Stdout )); try!( stdin_handle.read_line( &mut input_buffer ) .map_err( |_| RedError::Stdin )); match input_buffer.pop() { Some(x) => assert_eq!( x, '\n' ), None => {}, } if !RE.is_match( &mut input_buffer ) { break; } prompt = PROMPT_CONTINUE; } Ok( input_buffer ) } pub fn command_output( _full_stdin: &str ) -> String { let command: String; let arguments: Vec<String>; match compose_command( _full_stdin ) { ( cmd, args ) => { command = cmd; arguments = args; }, } let output: Output; if arguments[0].len() == 0 { output = Command::new( &command ) .output().expect("command failed"); } else { output = Command::new( &command ).args( &arguments ) .output().expect("command failed"); } let output_stdout = output.stdout; String::from_utf8( output_stdout ) .expect("Failed to get output") } fn compose_command( _full_stdin: &str ) -> ( String, Vec<String> ) { let arguments: Vec<String>; match split_cmd_args( _full_stdin ) { ( cmd, arg ) => { arguments = split_args( &arg ); ( cmd, arguments ) }, } } fn split_cmd_args( _full_stdin: &str ) -> ( String, String ) { let input = _full_stdin.trim(); let mut arguments = String::new(); let command: String; let first_space = input.find( char::is_whitespace ); match first_space { Some(x) => { match input.split_at( x ) { (zi, zf) => { command = zi.trim().to_string(); arguments = zf.trim().to_string(); }, } }, None => { command = input.trim().to_string(); }, } ( command, arguments ) } fn split_args( stringed: &str ) -> Vec<String> { let mut input = stringed.trim(); let mut argument = String::new(); let mut arguments: Vec<String> = Vec::new(); loop { let next_space = input.trim().find( char::is_whitespace ); match next_space { Some(x) => { match input.split_at( x ) { (zi, zf) => { input = zf.trim(); argument = argument + zi.trim(); if !is_quoted( stringed, x ) { arguments.push( argument ); argument = String::new(); } }, } }, None => { assert!( argument.is_empty(), "command_output: unterminated quote" ); arguments.push( input.to_string() ); break; }, } } arguments } pub fn is_quoted( text: &str, indx: usize ) -> bool { let bra: Vec<char> = vec!('(', '[', '{'); let ket: Vec<char> = vec!(')', ']', '}'); let quot: Vec<char> = vec!('"', '\'', '`'); let mut c_braket: Vec<isize> = vec!( 0; bra.len() ); let mut c_quote: Vec<isize> = vec!( 0; quot.len() ); let mut escaped: bool = false; let mut move_on: bool; let (left, _) = text.split_at( indx ); for ch in left.chars() { move_on = false; if ch == '\\' { escaped = !escaped; continue } for i in 0 .. quot.len() { if ch == quot[i] { if !escaped { c_quote[i] = 1 - c_quote[i]; } move_on = true; escaped = false; } } if move_on { continue } for i in 0 .. bra.len() { if ch == bra[i] { if c_quote == vec!( 0; c_quote.len() ) { if !escaped { c_braket[i] += 1; } move_on = true; escaped = false; } } } if move_on { continue } for i in 0 .. ket.len() { if ch == ket[i] { if c_quote == vec!( 0; c_quote.len() ) { if !escaped { c_braket[i] -= 1; } } } } escaped = false; } for sum in &c_braket { assert!( *sum >= 0, "is_quoted: too many closing brackets" ); } if c_quote == vec!( 0; c_quote.len() ) && c_braket == vec!( 0; c_braket.len() ) { false } else { true } }
/* * File : io.rs * Purpose: handles input/output functionality * Program: red * About : What does this program do? * Authors: Tommy Lincoln <pajamapants3000@gmail.com> * License: MIT; See LICENSE! * Notes : Notes on successful compilation * Created: 10/26/2016 */ use std::fs::{File, OpenOptions}; use std::path::Path; use std::process::{Command, Output}; use std::io::{self, BufRead, Write};
sum in &c_braket { assert!( *sum >= 0, "is_quoted: too many closing brackets" ); } if c_quote == vec!( 0; c_quote.len() ) && c_braket == vec!( 0; c_braket.len() ) { false } else { true } }
use std::ffi::OsStr; use regex::Regex; use error::*; use ::{EditorState, EditorMode}; const PROMPT_CONTINUE: &'static str = ">"; const PROMPT_INSERT: &'static str = "!"; #[derive(Default)] pub struct FileMode { pub f_write: bool, pub f_read: bool, pub f_append: bool, pub f_truncate: bool, pub f_create: bool, pub f_create_new: bool, } /* struct FileCoordinate { line: usize, col: usize, } */ /* /// Return next occurrence of regular expression regex_search( needle: &str, from: FileCoordinate ) -> FileCoordinate { } */ pub fn file_opener<S: AsRef<OsStr> + ?Sized>( name: &S, mode: FileMode ) -> Result<File, RedError> { OpenOptions::new() .read(mode.f_read) .write(mode.f_write) .append(mode.f_append) .truncate(mode.f_truncate) .create(mode.f_create) .create_new(mode.f_create_new) .open( Path::new(name) ).map_err(|err| RedError::FileOpen( err ) ) } pub fn get_input( mut input_buffer: String, state: &EditorState ) -> Result<String, RedError> { let stdin = io::stdin(); let stdout = io::stdout(); let mut stdin_handle = stdin.lock(); let mut stdout_handle = stdout.lock(); let mut prompt: &str; match state.mode { EditorMode::Command => prompt = &state.prompt, EditorMode::Insert => prompt = PROMPT_INSERT, } lazy_static! { static ref RE: Regex = Regex::new( r#".*\\"# ) .expect("get_input: failed to compile regex"); } loop { match input_buffer.pop() { Some(x) => { assert_eq!( x, '\\' ); input_buffer.push( '\n' ); }, None => {}, } try!( stdout_handle.write( prompt.as_bytes() ) .map_err( |_| RedError::Stdout )); try!( stdout_handle.flush().map_err( |_| RedError::Stdout )); try!( stdin_handle.read_line( &mut input_buffer ) .map_err( |_| RedError::Stdin )); match input_buffer.pop() { Some(x) => assert_eq!( x, '\n' ), None => {}, } if !RE.is_match( &mut input_buffer ) { break; } prompt = PROMPT_CONTINUE; } Ok( input_buffer ) } pub fn command_output( _full_stdin: &str ) -> String { let command: String; let arguments: Vec<String>; match compose_command( _full_stdin ) { ( cmd, args ) => { command = cmd; arguments = args; }, } let output: Output; if arguments[0].len() == 0 { output = Command::new( &command ) .output().expect("command failed"); } else { output = Command::new( &command ).args( &arguments ) .output().expect("command failed"); } let output_stdout = output.stdout; String::from_utf8( output_stdout ) .expect("Failed to get output") } fn compose_command( _full_stdin: &str ) -> ( String, Vec<String> ) { let arguments: Vec<String>; match split_cmd_args( _full_stdin ) { ( cmd, arg ) => { arguments = split_args( &arg ); ( cmd, arguments ) }, } } fn split_cmd_args( _full_stdin: &str ) -> ( String, String ) { let input = _full_stdin.trim(); let mut arguments = String::new(); let command: String; let first_space = input.find( char::is_whitespace ); match first_space { Some(x) => { match input.split_at( x ) { (zi, zf) => { command = zi.trim().to_string(); arguments = zf.trim().to_string(); }, } }, None => { command = input.trim().to_string(); }, } ( command, arguments ) } fn split_args( stringed: &str ) -> Vec<String> { let mut input = stringed.trim(); let mut argument = String::new(); let mut arguments: Vec<String> = Vec::new(); loop { let next_space = input.trim().find( char::is_whitespace ); match next_space { Some(x) => { match input.split_at( x ) { (zi, zf) => { input = zf.trim(); argument = argument + zi.trim(); if !is_quoted( stringed, x ) { arguments.push( argument ); argument = String::new(); } }, } }, None => { assert!( argument.is_empty(), "command_output: unterminated quote" ); arguments.push( input.to_string() ); break; }, } } arguments } pub fn is_quoted( text: &str, indx: usize ) -> bool { let bra: Vec<char> = vec!('(', '[', '{'); let ket: Vec<char> = vec!(')', ']', '}'); let quot: Vec<char> = vec!('"', '\'', '`'); let mut c_braket: Vec<isize> = vec!( 0; bra.len() ); let mut c_quote: Vec<isize> = vec!( 0; quot.len() ); let mut escaped: bool = false; let mut move_on: bool; let (left, _) = text.split_at( indx ); for ch in left.chars() { move_on = false; if ch == '\\' { escaped = !escaped; continue } for i in 0 .. quot.len() { if ch == quot[i] { if !escaped { c_quote[i] = 1 - c_quote[i]; } move_on = true; escaped = false; } } if move_on { continue } for i in 0 .. bra.len() { if ch == bra[i] { if c_quote == vec!( 0; c_quote.len() ) { if !escaped { c_braket[i] += 1; } move_on = true; escaped = false; } } } if move_on { continue } for i in 0 .. ket.len() { if ch == ket[i] { if c_quote == vec!( 0; c_quote.len() ) { if !escaped { c_braket[i] -= 1; } } } } escaped = false; } for
random
[ { "content": "/// Print help, warnings, other output depending on setting\n\n///\n\n/// TODO: Change first arg to just boolean: state.help?\n\npub fn print_help<T: Display>( state: &EditorState, output: T ) {// {{{\n\n if state.show_help {\n\n println!( \"{}\", output );\n\n } else {\n\n pri...
Rust
oracle/src/connection.rs
foundation-rs/backend
cc16dff0879314dd05494581aa580c23c74d282f
#[allow(dead_code)] #[allow(non_snake_case)] #[allow(non_camel_case_types)] use crate::oci; use crate::environment::Environment; use crate::{statement, OracleResult, SQLParams, ParamsProvider, SQLResults}; /* pub struct Connection { env: &'static Environment, srvhp: *mut oci::OCIServer, authp: *mut oci::OCISession, pub(crate) errhp: *mut oci::OCIError, pub(crate) svchp: *mut oci::OCISvcCtx, } */ pub struct SessionPool { env: &'static Environment, pub(crate) errhp: *const oci::OCIError, poolhp: *const oci::OCISPool, poolname: String, } unsafe impl Sync for SessionPool {} unsafe impl Send for SessionPool {} pub struct Connection { env: &'static Environment, pub(crate) errhp: *mut oci::OCIError, pub(crate) svchp: *mut oci::OCISvcCtx, } pub fn create_pool(db: &str, username: &str, passwd: &str) -> OracleResult<SessionPool> { let env = Environment::get()?; let errhp = env.errhp; let (poolhp, poolname) = oci::create_session_pool(env.envhp, errhp, 1,2, db, username, passwd)?; Ok(SessionPool{env, errhp, poolhp, poolname }) } impl SessionPool { pub fn connect(&self) -> OracleResult<Connection> { let svchp = oci::session_get(self.env.envhp, self.errhp as *mut oci::OCIError, &self.poolname)?; Ok( Connection::new(self.env, self.errhp as *mut oci::OCIError, svchp) ) } } impl Drop for SessionPool { fn drop(&mut self) { oci::destroy_session_pool(self.poolhp as *mut oci::OCISPool, self.errhp as *mut oci::OCIError).unwrap(); } } impl Drop for Connection { fn drop(&mut self) { oci::session_release(self.svchp, self.errhp); } } /* pub fn connect(db: &str, username: &str, passwd: &str) -> OracleResult<Connection> { let env = Environment::get()?; let srvhp = oci::handle_alloc(env.envhp, oci::OCI_HTYPE_SERVER)? as *mut oci::OCIServer; let svchp = oci::handle_alloc(env.envhp, oci::OCI_HTYPE_SVCCTX)? as *mut oci::OCISvcCtx; let errhp = env.errhp; let res = oci::server_attach(srvhp, errhp, db); if let Err(err) = res { free_server_handlers(srvhp, svchp); return Err(err); }; // set attribute server context in the service context oci::attr_set(svchp as *mut oci::c_void, oci::OCI_HTYPE_SVCCTX, srvhp as *mut oci::c_void, 0, oci::OCI_ATTR_SERVER, errhp)?; let authp = oci::prepare_auth(env.envhp, errhp, username, passwd)?; let res = oci::session_begin(svchp, errhp, authp); if let Err(err) = res { free_session_handler(authp); free_server_handlers(srvhp, svchp); return Err(err); }; // set session context in the service context oci::attr_set(svchp as *mut oci::c_void, oci::OCI_HTYPE_SVCCTX, authp as *mut oci::c_void, 0, oci::OCI_ATTR_SESSION, errhp)?; return Ok( Connection::new(env, srvhp, authp, errhp, svchp ) ); } */ impl Connection { fn new(env: &'static Environment, errhp: *mut oci::OCIError, svchp: *mut oci::OCISvcCtx) -> Connection { Connection { env, errhp, svchp } } pub fn commit(&self) -> OracleResult<()> { oci::commit(self.svchp, self.env.errhp) } pub fn rollback(&self) -> OracleResult<()> { oci::rollback(self.svchp, self.env.errhp) } pub fn execute<'conn,'s>(&'conn self, sql: &'s str) -> OracleResult<()> { let st = statement::Statement::new(self, sql, Box::new(()))?; st.execute(()) } pub fn prepare<P>(&self, sql: &str) -> OracleResult<statement::Statement<P>> where P: SQLParams { let provider = P::provider(); statement::Statement::new(self, sql, provider) } pub fn prepare_dynamic<P>(&self, sql: &str, provider: Box<dyn ParamsProvider<P>>) -> OracleResult<statement::Statement<P>> { statement::Statement::new(self, sql, provider) } pub fn query<'conn, P, R: 'conn>(&'conn self, sql: &str) -> OracleResult<statement::Query<'conn, P,R>> where P: SQLParams, R: SQLResults { let provider = P::provider(); statement::Statement::new(self, sql, provider)?.query() } pub fn query_one<'conn, P,R: 'conn>(&'conn self, sql: &str) -> OracleResult<statement::Query<'conn, P,R>> where P: SQLParams, R: SQLResults { let provider = P::provider(); statement::Statement::new(self, sql, provider)?.query_one() } } /* impl Drop for Connection { fn drop(&mut self) { oci::session_end(self.svchp, self.env.errhp, self.authp); oci::server_detach(self.srvhp, self.env.errhp); free_session_handler(self.authp); free_server_handlers(self.srvhp, self.svchp); } } */ fn free_session_handler(authp: *mut oci::OCISession) { if !authp.is_null() { oci::handle_free(authp as *mut oci::c_void, oci::OCI_HTYPE_SESSION); } } fn free_server_handlers(srvhp: *mut oci::OCIServer, svchp: *mut oci::OCISvcCtx) { if !svchp.is_null() { oci::handle_free(svchp as *mut oci::c_void, oci::OCI_HTYPE_SVCCTX); } if !srvhp.is_null() { oci::handle_free(srvhp as *mut oci::c_void, oci::OCI_HTYPE_SERVER); } }
#[allow(dead_code)] #[allow(non_snake_case)] #[allow(non_camel_case_types)] use crate::oci; use crate::environment::Environment; use crate::{statement, OracleResult, SQLParams, ParamsProvider, SQLResults}; /* pub struct Connection { env: &'static Environment, srvhp: *mut oci::OCIServer, authp: *mut oci::OCISession, pub(crate) errhp: *mut oci::OCIError, pub(crate) svchp: *mut oci::OCISvcCtx, } */ pub struct SessionPool { env: &'static Environment, pub(crate) errhp: *const oci::OCIError, poolhp: *const oci::OCISPool, poolname: String, } unsafe impl Sync for SessionPool {} unsafe impl Send for SessionPool {} pub struct Connection { env: &'static Environment, pub(crate) errhp: *mut oci::OCIError, pub(crate) svchp: *mut oci::OCISvcCtx, } pub fn create_pool(db: &str, username: &str, passwd: &str) -> OracleResult<SessionPool> { let env = Environment::get()?; let errhp = env.errhp; let (poolhp, poolname) = oci::create_session_pool(env.envhp, errhp, 1,2, db, username, passwd)?; Ok(SessionPool{env, errhp, poolhp, poolname }) } impl SessionPool { pub fn connect(&self) -> OracleResult<Connection> { let svchp = oci::session_get(self.env.envhp, self.errhp as *mut oci::OCIError, &self.poolname)?; Ok( Connection::new(self.env, self.errhp as *mut oci::OCIError, svchp) ) } } impl Drop for SessionPool { fn drop(&mut self) { oci::destroy_session_pool(self.poolhp as *mut oci::OCISPool, self.errhp as *mut oci::OCIError).unwrap(); } } impl Drop for Connection { fn drop(&mut self) { oci::session_release(self.svchp, self.errhp); } } /* pub fn connect(db: &str, username: &str, passwd: &str) -> OracleResult<Connection> { let env = Environment::get()?; let srvhp
one() } } /* impl Drop for Connection { fn drop(&mut self) { oci::session_end(self.svchp, self.env.errhp, self.authp); oci::server_detach(self.srvhp, self.env.errhp); free_session_handler(self.authp); free_server_handlers(self.srvhp, self.svchp); } } */ fn free_session_handler(authp: *mut oci::OCISession) { if !authp.is_null() { oci::handle_free(authp as *mut oci::c_void, oci::OCI_HTYPE_SESSION); } } fn free_server_handlers(srvhp: *mut oci::OCIServer, svchp: *mut oci::OCISvcCtx) { if !svchp.is_null() { oci::handle_free(svchp as *mut oci::c_void, oci::OCI_HTYPE_SVCCTX); } if !srvhp.is_null() { oci::handle_free(srvhp as *mut oci::c_void, oci::OCI_HTYPE_SERVER); } }
= oci::handle_alloc(env.envhp, oci::OCI_HTYPE_SERVER)? as *mut oci::OCIServer; let svchp = oci::handle_alloc(env.envhp, oci::OCI_HTYPE_SVCCTX)? as *mut oci::OCISvcCtx; let errhp = env.errhp; let res = oci::server_attach(srvhp, errhp, db); if let Err(err) = res { free_server_handlers(srvhp, svchp); return Err(err); }; // set attribute server context in the service context oci::attr_set(svchp as *mut oci::c_void, oci::OCI_HTYPE_SVCCTX, srvhp as *mut oci::c_void, 0, oci::OCI_ATTR_SERVER, errhp)?; let authp = oci::prepare_auth(env.envhp, errhp, username, passwd)?; let res = oci::session_begin(svchp, errhp, authp); if let Err(err) = res { free_session_handler(authp); free_server_handlers(srvhp, svchp); return Err(err); }; // set session context in the service context oci::attr_set(svchp as *mut oci::c_void, oci::OCI_HTYPE_SVCCTX, authp as *mut oci::c_void, 0, oci::OCI_ATTR_SESSION, errhp)?; return Ok( Connection::new(env, srvhp, authp, errhp, svchp ) ); } */ impl Connection { fn new(env: &'static Environment, errhp: *mut oci::OCIError, svchp: *mut oci::OCISvcCtx) -> Connection { Connection { env, errhp, svchp } } pub fn commit(&self) -> OracleResult<()> { oci::commit(self.svchp, self.env.errhp) } pub fn rollback(&self) -> OracleResult<()> { oci::rollback(self.svchp, self.env.errhp) } pub fn execute<'conn,'s>(&'conn self, sql: &'s str) -> OracleResult<()> { let st = statement::Statement::new(self, sql, Box::new(()))?; st.execute(()) } pub fn prepare<P>(&self, sql: &str) -> OracleResult<statement::Statement<P>> where P: SQLParams { let provider = P::provider(); statement::Statement::new(self, sql, provider) } pub fn prepare_dynamic<P>(&self, sql: &str, provider: Box<dyn ParamsProvider<P>>) -> OracleResult<statement::Statement<P>> { statement::Statement::new(self, sql, provider) } pub fn query<'conn, P, R: 'conn>(&'conn self, sql: &str) -> OracleResult<statement::Query<'conn, P,R>> where P: SQLParams, R: SQLResults { let provider = P::provider(); statement::Statement::new(self, sql, provider)?.query() } pub fn query_one<'conn, P,R: 'conn>(&'conn self, sql: &str) -> OracleResult<statement::Query<'conn, P,R>> where P: SQLParams, R: SQLResults { let provider = P::provider(); statement::Statement::new(self, sql, provider)?.query_
random
[]
Rust
src/systems/cursor_system.rs
csherratt/everpuzzle
6ac83fa7652d1e2d51f23a6f78ef16e27f11a94d
use amethyst::{ ecs::*, core::Transform, renderer::*, input::* }; use components::{ block::Block, cursor::Cursor, kind_generator::KindGenerator, playfield::stack::Stack, }; use block_states::swap::SWAP_TIME; use block_states::block_state::change_state; use data::block_data::*; use std::collections::HashMap; pub struct CursorSystem { key_presses: HashMap<String, i32> } impl CursorSystem { pub fn new() -> CursorSystem { let mut key_presses: HashMap<String, i32> = HashMap::new(); key_presses.insert(String::from("up"), 0); key_presses.insert(String::from("down"), 0); key_presses.insert(String::from("right"), 0); key_presses.insert(String::from("left"), 0); key_presses.insert(String::from("swap"), 0); key_presses.insert(String::from("space"), 0); key_presses.insert(String::from("raise"), 0); CursorSystem { key_presses } } pub fn hold(&mut self, input: &mut Read<InputHandler<String, String>>, name: &str) -> bool { if input.action_is_down(name).unwrap() { let result = *self.key_presses.get(name).unwrap(); if result == 0 || result > 16 { *self.key_presses.get_mut(name).unwrap() += 1; return true; } *self.key_presses.get_mut(name).unwrap() += 1; } else { *self.key_presses.get_mut(name).unwrap() = 0; } return false; } pub fn press(&mut self, input: &mut Read<InputHandler<String, String>>, name: &str) -> bool { if input.action_is_down(name).unwrap() { if *self.key_presses.get(name).unwrap() == 0 { *self.key_presses.get_mut(name).unwrap() = 1; return true; } } else { *self.key_presses.get_mut(name).unwrap() = 0; } return false; } } impl<'a> System<'a> for CursorSystem { type SystemData = ( WriteStorage<'a, SpriteRender>, WriteStorage<'a, Transform>, WriteStorage<'a, Cursor>, Read<'a, InputHandler<String, String>>, Write<'a, KindGenerator>, WriteStorage<'a, Block>, ReadStorage<'a, Stack>, ); fn run(&mut self, ( mut sprites, mut transforms, mut cursors, mut input, mut kind_gen, mut blocks, stacks, ): Self::SystemData) { if self.hold(&mut input, "up") { for cursor in (&mut cursors).join() { if cursor.y < (ROWS - 1) as f32 { cursor.y += 1.0; } } } if self.hold(&mut input, "down") { for cursor in (&mut cursors).join() { if cursor.y > 1.0 { cursor.y -= 1.0; } } } if self.hold(&mut input, "left") { for cursor in (&mut cursors).join() { if cursor.x > 0.0 { cursor.x -= 1.0; } } } if self.hold(&mut input, "right") { for cursor in (&mut cursors).join() { if cursor.x < (COLS - 2) as f32 { cursor.x += 1.0; } } } if self.press(&mut input, "space") { let kinds = kind_gen.create_stack(5, 8); for stack in (&stacks).join() { for i in 0..BLOCKS { blocks.get_mut(stack.from_i(i)).unwrap().kind = kinds[i]; } } } if self.press(&mut input, "swap") { for cursor in (cursors).join() { for stack in (&stacks).join() { swap(cursor.x, cursor.y, &stack, &mut blocks); } } } if self.press(&mut input, "raise") { for cursor in cursors.join() { for stack in (&stacks).join() { } } } for (sprite, transform, cursor) in (&mut sprites, &mut transforms, &mut cursors).join() { cursor.set_position(transform); sprite.sprite_number = cursor.anim_offset as usize; if cursor.anim_offset < 7.0 { cursor.anim_offset += 1.0 / 4.0; } else { cursor.anim_offset = 0.0; } } } } fn swap( x: f32, y: f32, stack: &Stack, blocks: &mut WriteStorage<'_, Block>) { let i = Stack::xy2i(x as usize, y as usize); let mut can_swap: bool = false; { let b1 = blocks.get(stack.from_i(i)).unwrap(); let b2 = blocks.get(stack.from_i(i + 1)).unwrap(); let mut b1_above_block: Option<&Block> = None; let mut b2_above_block: Option<&Block> = None; if i < BLOCKS - COLS { b1_above_block = blocks.get(stack.from_i(i + COLS)); b2_above_block = blocks.get(stack.from_i(i + 1 + COLS)); } if b1.is_swappable(b2, b1_above_block) && b2.is_swappable(b1, b2_above_block) { if b1.is_empty() && b2.is_empty() { return; } can_swap = true; } } if can_swap { set_swap_variables(blocks.get_mut(stack.from_i(i)).unwrap(), 1.0); set_swap_variables(blocks.get_mut(stack.from_i(i + 1)).unwrap(), -1.0); let mut left_block = Block::default(); let mut right_block = Block::default(); left_block = blocks.get(stack.from_i(i)) .unwrap() .clone(); right_block = blocks.get(stack.from_i(i + 1)) .unwrap() .clone(); { blocks.get_mut(stack.from_i(i + 1)) .unwrap() .set_properties(left_block); } { blocks.get_mut(stack.from_i(i)) .unwrap() .set_properties(right_block); } } } fn set_swap_variables (b: &mut Block, dir: f32) { b.offset.0 = 16.0 * dir; b.counter = SWAP_TIME as u32; b.move_dir = dir; change_state(b, "SWAP"); }
use amethyst::{ ecs::*, core::Transform, renderer::*, input::* }; use components::{ block::Block, cursor::Cursor, kind_generator::KindGenerator, playfield::stack::Stack, }; use block_states::swap::SWAP_TIME; use block_states::block_state::change_state; use data::block_data::*; use std::collections::HashMap; pub struct CursorSystem { key_presses: HashMap<String, i32> } impl CursorSystem { pub fn new() -> CursorSystem { let mut key_presses: HashMap<String, i32> = HashMap::new(); key_presses.insert(String::from("up"), 0); key_presses.insert(String::from("down"), 0); key_presses.insert(String::from("right"), 0); key_presses.insert(String::from("left"), 0); key_presses.insert(String::from("swap"), 0); key_presses.insert(String::from("space"), 0); key_presses.insert(String::from("raise"), 0); CursorSystem { key_presses } } pub fn hold(&mut self, input: &mut Read<InputHandler<String, String>>, name: &str) -> bool { if input.action_is_down(name).unwrap() { let result = *self.key_presses.get(name).unwrap(); if result == 0 || result > 16 { *self.key_presses.get_mut(name).unwrap() += 1; return true; } *self.key_presses.get_mut(name).unwrap() += 1; } else { *self.key_presses.get_mut(name).unwrap() = 0; } return false; } pub fn press(&mut self, input: &mut Read<InputHandler<String, String>>, name: &str) -> bool { if input.action_is_down(name).unwrap() { if *self.key_presses.get(name).unwrap() == 0 { *self.key_presses.get_mut(name).unwrap() = 1; return true; } } else { *self.key_presses.get_mut(name).unwrap() = 0; } return false; } } impl<'a> System<'a> for CursorSystem { type SystemData = ( WriteStorage<'a, SpriteRender>, WriteStorage<'a, Transform>, WriteStorage<'a, Cursor>, Read<'a, InputHandler<String, String>>, Write<'a, KindGenerator>, WriteStorage<'a, Block>, ReadStorage<'a, Stack>, ); fn run(&mut self, ( mut sprites, mut transforms, mut cursors, mut input, mut kind_gen, mut blocks, stacks, ): Self::SystemData) { if self.hold(&mut input, "up") { for cursor in (&mut cursors).join() { if cursor.y < (ROWS - 1) as f32 { cursor.y += 1.0; } } } if self.hold(&mut input, "down") { for cursor in (&mut cursors).join() { if cursor.y > 1.0 { cursor.y -= 1.0; } } } if self.hold(&mut input, "left") { for cursor in (&mut cursors).join() { if cursor.x > 0.0 { cursor.x -= 1.0; } } } if self.hold(&mut input, "right") { for cursor in (&mut cursors).join() { if cursor.x < (COLS - 2) as f32 { cursor.x += 1.0; } } } if self.press(&mut input, "space") { let kinds = kind_gen.create_stack(5, 8); for stack in (&stacks).join() { for i in 0..BLOCKS { blocks.get_mut(stack.from_i(i)).unwrap().kind = kinds[i]; } } } if self.press(&mut input, "swap") { for cursor in (cursors).join() { for stack in (&stacks).join() { swap(cursor.x, cursor.y, &stack, &mut blocks); } } } if self.press(&mut input, "raise") { for cursor in cursors.join() { for stack in (&stacks).join() { } } } for (sprite, transform, cursor) in (&mut sprites, &mut transforms, &mut cursors).join() { cursor.set_position(transform); sprite.sprite_number = cursor.anim_offset as usize; if cursor.anim_offset < 7.0 { cursor.anim_offset += 1.0 / 4.0; } else { cursor.anim_offset = 0.0; } } } } fn swap( x: f32, y: f32, stack: &Stack, blocks: &mut WriteStorage<'_, Block>) { let i = Stack::xy2i(x as usize, y as usize); let mut can_swap: bool = false; { let b1 = blocks.get(stack.from_i(i)).unwrap(); let b2 = blocks.get(stack.from_i(i + 1)).unwrap(); let mut b1_above_block: Option<&Block> = None; let mut b2_above_block: Option<&Block> = None; if i < BLOCKS - COLS { b1_above_block = blocks.get(stack.from_i(i + COLS)); b2_above_block = blocks.get(stack.from_i(i + 1 + COLS)); } if b1.is_swappable(b2, b1_above_block) && b2.is_swappable(b1, b2_above_block) { if b1.is_empty() && b2.is_empty() { return; } can_swap = true; } } if can_swap { set_swap_variables(blocks.get_mut(stack.from_i(i)).unwrap(), 1.0); set_swap_variables(blocks.get_mut(stack.from_i(i + 1)).unwrap(), -1.0); let mut left_block = Block::default(); let mut right_block = Block::default(); left_block = blocks.get(stack.from_i(i)) .unwrap() .clone(); right_block = blocks.get(stack.from_i(i + 1)) .unwrap() .clone(); { blocks.get_mut(stack.from_i(i + 1)) .unwrap() .set_properties(left_block); } { blocks.get_mut(stack.from_i(i)) .unwrap() .set_properties(right_block); } } }
fn set_swap_variables (b: &mut Block, dir: f32) { b.offset.0 = 16.0 * dir; b.counter = SWAP_TIME as u32; b.move_dir = dir; change_state(b, "SWAP"); }
function_block-full_function
[ { "content": "// checks wether the block below is empty or falling, also checks wether this block is empty\n\npub fn check_for_hang(i: usize, stack: &Stack, blocks: &mut WriteStorage<'_, Block>) -> bool {\n\n // condition based on another block in a different lifetime\n\n let mut down_condition: bool = fa...
Rust
AoC_2021/Day08_SevenSegmentSearch_Rust/src/main.rs
jgpr-code/AdventOfCode
f529af8d7cb74348405679b76062807827b35a29
use itertools::Itertools; use std::collections::{HashMap, HashSet}; use std::io::{self, Read}; fn main() -> io::Result<()> { let mut stdin = io::stdin(); let mut buffer = String::new(); stdin.read_to_string(&mut buffer)?; part_one(&buffer); part_two(&buffer); Ok(()) } fn parse_input(buffer: &str) -> Vec<(Vec<&str>, Vec<&str>)> { let mut output = Vec::new(); for line in buffer.lines() { let mut pipe_split = line.split("|"); let digits: Vec<&str> = pipe_split .nth(0) .unwrap() .split_whitespace() .filter(|s| s.len() > 0) .collect(); let output_digits: Vec<&str> = pipe_split .nth(0) .unwrap() .split_whitespace() .filter(|s| s.len() > 0) .collect(); output.push((digits, output_digits)); } output } fn part_one(buffer: &str) { let input = parse_input(buffer); let sum = input.iter().fold(0, |acc, (_, out)| { acc + out.iter().filter(|x| is_simple_digit(x)).count() }); println!("Part 1: {}", sum); } fn is_simple_digit(digit: &str) -> bool { let len = digit.len(); len == 2 || len == 4 || len == 3 || len == 7 } fn part_two(buffer: &str) { let input = parse_input(buffer); let answer = input.iter().fold(0, |acc, (d, od)| acc + decode(d, od)); println!("Part 2: {}", answer); } fn decode(digits: &Vec<&str>, output_digits: &Vec<&str>) -> i32 { let decodings = possible_decodings(); for decoding in decodings.iter() { if let Some(mapping) = digit_mapping(digits, decoding) { let mut thousands_chars: Vec<char> = output_digits[0].chars().collect(); thousands_chars.sort(); let thousands = mapping[&thousands_chars]; let mut hundreds_chars: Vec<char> = output_digits[1].chars().collect(); hundreds_chars.sort(); let hundreds = mapping[&hundreds_chars]; let mut tens_chars: Vec<char> = output_digits[2].chars().collect(); tens_chars.sort(); let tens = mapping[&tens_chars]; let mut ones_chars: Vec<char> = output_digits[3].chars().collect(); ones_chars.sort(); let ones = mapping[&ones_chars]; return 1000 * thousands + 100 * hundreds + 10 * tens + ones; } } 0 } fn possible_decodings() -> Vec<HashMap<char, i32>> { let perms: Vec<Vec<i32>> = (0..7).permutations(7).collect(); let chars = vec!['a', 'b', 'c', 'd', 'e', 'f', 'g']; let mut mappings = Vec::new(); for perm in perms.iter() { let mut mapping = HashMap::new(); for (c, i) in chars.iter().zip(perm) { mapping.insert(*c, *i); } mappings.push(mapping); } mappings } fn digit_mapping<'a>( digits: &Vec<&'a str>, decoding: &HashMap<char, i32>, ) -> Option<HashMap<Vec<char>, i32>> { let mut digit_mapping = HashMap::new(); for digit in digits.iter() { let segments = digit_to_segments(digit, decoding); if let Some(int_digit) = segments_to_digit(&segments) { let mut sorted_chars: Vec<char> = digit.chars().collect(); sorted_chars.sort(); digit_mapping.insert(sorted_chars, int_digit); } } if is_valid_mapping(&digit_mapping) { Some(digit_mapping) } else { None } } fn is_valid_mapping(digit_mapping: &HashMap<Vec<char>, i32>) -> bool { let values_set: HashSet<&i32> = digit_mapping.values().collect(); for i in 0..10 { if !values_set.contains(&i) { return false; } } if values_set.iter().count() != 10 { return false; } true } fn digit_to_segments(digit: &str, decoding: &HashMap<char, i32>) -> Vec<i32> { let mut segment_vec: Vec<i32> = digit.chars().map(|c| decoding[&c]).collect(); segment_vec.sort(); segment_vec } fn segments_to_digit(segments: &Vec<i32>) -> Option<i32> { match segments[..] { [0, 1, 2, 4, 5, 6] => Some(0), [2, 5] => Some(1), [0, 2, 3, 4, 6] => Some(2), [0, 2, 3, 5, 6] => Some(3), [1, 2, 3, 5] => Some(4), [0, 1, 3, 5, 6] => Some(5), [0, 1, 3, 4, 5, 6] => Some(6), [0, 2, 5] => Some(7), [0, 1, 2, 3, 4, 5, 6] => Some(8), [0, 1, 2, 3, 5, 6] => Some(9), _ => None, } }
use itertools::Itertools; use std::collections::{HashMap, HashSet}; use std::io::{self, Read}; fn main() -> io::Result<()> { let mut stdin = io::stdin(); let mut buffer = String::new(); stdin.read_to_string(&mut buffer)?; part_one(&buffer); part_two(&buffer); Ok(()) } fn parse_input(buffer: &str) -> Vec<(Vec<&str>, Vec<&str>)> { let mut output = Vec::new(); for line in buffer.lines() { let mut pipe_split = line.split("|"); let digits: Vec<&str> = pipe_split .nth(0) .unwrap() .split_whitespace() .filter(|s| s.len() > 0) .collect(); let output_digits: Vec<&str> = pipe_split .nth(0) .unwrap() .split_whitespace() .filter(|s| s.len() > 0) .collect(); output.push((digits, output_digits)); } output } fn part_one(buffer: &str) { let input = parse_input(buffer); let sum = input.iter().fold(0, |acc, (_, out)| { acc + out.iter().filter(|x| is_simple_digit(x)).count() }); println!("Part 1: {}", sum); } fn is_simple_digit(digit: &str) -> bool { let len = digit.len(); len == 2 || len == 4 || len == 3 || len == 7 } fn part_two(buffer: &str) { let input = parse_input(buffer); let answer = input.iter().fold(0, |acc, (d, od)| acc + decode(d, od)); println!("Part 2: {}", answer); } fn decode(digits: &Vec<&str>, output_digits: &Vec<&str>) -> i32 { let decodings = possible_decodings(); for decoding in decodings.iter() { if let Some(mapping) = digit_mapping(digits, decoding) { let mut thousands_chars: Vec<char> = output_digits[0].chars().collect(); thousands_chars.sort(); let thousands = mapping[&thousands_chars]; let mut hundreds_chars: Vec<char> = output_digits[1].chars().collect(); hundreds_chars.sort(); let hundreds = mapping[&hundreds_chars]; let mut tens_chars: Vec<char> = output_digits[2].chars().collect(); tens_chars.sort(); let tens = mapping[&tens_chars]; let mut ones_chars: Vec<char> = output_digits[3].chars().collect(); ones_chars.sort(); let ones = mapping[&ones_chars]; return 1000 * thousands + 100 * hundreds + 10 * tens + ones; } } 0 } fn possible_decodings() -> Vec<HashMap<char, i32>> { let perms: Vec<Vec<i32>> = (0..7).permutations(7).collect(); let chars = vec!['a', 'b', 'c', 'd', 'e', 'f', 'g']; let mut mappings = Vec::new(); for perm in perms.iter() { let mut mapping = HashMap::new(); for (c, i) in chars.iter().zip(perm) { mapping.insert(*c, *i); } mappings.push(mapping); } mappings } fn digit_mapping<'a>( digits: &Vec<&'a str>, decoding: &HashMap<char, i32>, ) -> Option<HashMap<Vec<char>, i32>> { let mut digit_mapping = HashMap::new(); for digit in digits.iter() { let segments = digit_to_segments(digit, decoding);
} if is_valid_mapping(&digit_mapping) { Some(digit_mapping) } else { None } } fn is_valid_mapping(digit_mapping: &HashMap<Vec<char>, i32>) -> bool { let values_set: HashSet<&i32> = digit_mapping.values().collect(); for i in 0..10 { if !values_set.contains(&i) { return false; } } if values_set.iter().count() != 10 { return false; } true } fn digit_to_segments(digit: &str, decoding: &HashMap<char, i32>) -> Vec<i32> { let mut segment_vec: Vec<i32> = digit.chars().map(|c| decoding[&c]).collect(); segment_vec.sort(); segment_vec } fn segments_to_digit(segments: &Vec<i32>) -> Option<i32> { match segments[..] { [0, 1, 2, 4, 5, 6] => Some(0), [2, 5] => Some(1), [0, 2, 3, 4, 6] => Some(2), [0, 2, 3, 5, 6] => Some(3), [1, 2, 3, 5] => Some(4), [0, 1, 3, 5, 6] => Some(5), [0, 1, 3, 4, 5, 6] => Some(6), [0, 2, 5] => Some(7), [0, 1, 2, 3, 4, 5, 6] => Some(8), [0, 1, 2, 3, 5, 6] => Some(9), _ => None, } }
if let Some(int_digit) = segments_to_digit(&segments) { let mut sorted_chars: Vec<char> = digit.chars().collect(); sorted_chars.sort(); digit_mapping.insert(sorted_chars, int_digit); }
if_condition
[ { "content": "fn parse_input(buffer: &str) -> Vec<LineSegment> {\n\n buffer.lines().map(|line| LineSegment::new(line)).collect()\n\n}\n\n\n", "file_path": "AoC_2021/Day05_HydrothermalVenture_Rust/src/main.rs", "rank": 4, "score": 217899.7567314388 }, { "content": "fn parse_input(buffer: &...
Rust
src/api/boblight.rs
vtavernier/hyperion.rs
18cf772ffb649edff4445361741659760e084393
use std::sync::Arc; use thiserror::Error; use crate::{ global::{InputMessage, InputMessageData, InputSourceHandle, Message, PriorityGuard}, instance::{InstanceHandle, InstanceHandleError}, models::Color, }; pub mod message; use message::{BoblightRequest, BoblightResponse}; #[derive(Debug, Error)] pub enum BoblightApiError { #[error("error broadcasting update: {0}")] Broadcast(#[from] tokio::sync::mpsc::error::SendError<InputMessage>), #[error("missing command data in protobuf frame")] MissingCommand, #[error("invalid instance")] InvalidInstance(#[from] InstanceHandleError), } pub struct ClientConnection { handle: InputSourceHandle<InputMessage>, priority_guard: PriorityGuard, led_colors: Vec<Color>, priority: i32, instance: InstanceHandle, } impl ClientConnection { pub fn new( handle: InputSourceHandle<InputMessage>, led_count: usize, instance: InstanceHandle, ) -> Self { let priority_guard = PriorityGuard::new_mpsc(instance.input_channel().clone(), &handle); Self { handle, priority_guard, led_colors: vec![Color::default(); led_count], priority: 128, instance, } } async fn set_priority(&mut self, priority: i32) { let new_priority = if priority < 128 || priority >= 254 { self.instance .current_priorities() .await .map(|priorities| { let mut used_priorities = priorities .iter() .map(|p| p.priority) .skip_while(|p| *p <= 128) .peekable(); for i in 128..255 { loop { match used_priorities.peek().cloned() { Some(used) if used == i => { used_priorities.next(); break; } Some(used) if used < i => { used_priorities.next(); continue; } _ => { return i; } } } } 128 }) .unwrap_or(128) } else { priority }; self.priority = new_priority; self.priority_guard.set_priority(Some(new_priority)); } async fn sync(&self) -> Result<(), BoblightApiError> { Ok(self .instance .send(InputMessage::new( self.handle.id(), crate::component::ComponentName::BoblightServer, InputMessageData::LedColors { priority: self.priority, duration: None, led_colors: Arc::new(self.led_colors.clone()), }, )) .await?) } #[instrument(skip(request))] pub async fn handle_request( &mut self, request: BoblightRequest, ) -> Result<Option<BoblightResponse>, BoblightApiError> { match request { BoblightRequest::Hello => Ok(Some(BoblightResponse::Hello)), BoblightRequest::Ping => Ok(Some(BoblightResponse::Ping)), BoblightRequest::Get(get) => match get { message::GetArg::Version => Ok(Some(BoblightResponse::Version)), message::GetArg::Lights => Ok(Some(BoblightResponse::Lights { leds: self.instance.config().await?.leds.leds.clone(), })), }, BoblightRequest::Set(set) => { match set { message::SetArg::Light(message::LightParam { index, data }) => match data { message::LightParamData::Color(color) => { if let Some(color_mut) = self.led_colors.get_mut(index) { *color_mut = color; if index == self.led_colors.len() - 1 { self.sync().await?; } } } _ => {} }, message::SetArg::Priority(priority) => { self.set_priority(priority).await; } } Ok(None) } BoblightRequest::Sync => { self.sync().await?; Ok(None) } } } } impl std::fmt::Debug for ClientConnection { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ClientConnection") .field("instance", &self.instance.id()) .field("source", &format!("{}", &*self.handle)) .finish() } }
use std::sync::Arc; use thiserror::Error; use crate::{ global::{InputMessage, InputMessageData, InputSourceHandle, Message, PriorityGuard}, instance::{InstanceHandle, InstanceHandleError}, models::Color, }; pub mod message; use message::{BoblightRequest, BoblightResponse}; #[derive(Debug, Error)] pub enum BoblightApiError { #[error("error broadcasting update: {0}")] Broadcast(#[from] tokio::sync::mpsc::error::SendError<InputMessage>), #[error("missing command data in protobuf frame")] MissingCommand, #[error("invalid instance")] InvalidInstance(#[from] InstanceHandleError), } pub struct ClientConnection { handle: InputSourceHandle<InputMessage>, priority_guard: PriorityGuard, led_colors: Vec<Color>, priority: i32, instance: InstanceHandle, } impl ClientConnection { pub fn new( handle: InputSourceHandle<InputMessage>, led_count: usize, instance: InstanceHandle, ) -> Self { let priority_guard = PriorityGuard::new_mpsc(instance.input_channel().clone(), &handle); Self {
async fn set_priority(&mut self, priority: i32) { let new_priority = if priority < 128 || priority >= 254 { self.instance .current_priorities() .await .map(|priorities| { let mut used_priorities = priorities .iter() .map(|p| p.priority) .skip_while(|p| *p <= 128) .peekable(); for i in 128..255 { loop { match used_priorities.peek().cloned() { Some(used) if used == i => { used_priorities.next(); break; } Some(used) if used < i => { used_priorities.next(); continue; } _ => { return i; } } } } 128 }) .unwrap_or(128) } else { priority }; self.priority = new_priority; self.priority_guard.set_priority(Some(new_priority)); } async fn sync(&self) -> Result<(), BoblightApiError> { Ok(self .instance .send(InputMessage::new( self.handle.id(), crate::component::ComponentName::BoblightServer, InputMessageData::LedColors { priority: self.priority, duration: None, led_colors: Arc::new(self.led_colors.clone()), }, )) .await?) } #[instrument(skip(request))] pub async fn handle_request( &mut self, request: BoblightRequest, ) -> Result<Option<BoblightResponse>, BoblightApiError> { match request { BoblightRequest::Hello => Ok(Some(BoblightResponse::Hello)), BoblightRequest::Ping => Ok(Some(BoblightResponse::Ping)), BoblightRequest::Get(get) => match get { message::GetArg::Version => Ok(Some(BoblightResponse::Version)), message::GetArg::Lights => Ok(Some(BoblightResponse::Lights { leds: self.instance.config().await?.leds.leds.clone(), })), }, BoblightRequest::Set(set) => { match set { message::SetArg::Light(message::LightParam { index, data }) => match data { message::LightParamData::Color(color) => { if let Some(color_mut) = self.led_colors.get_mut(index) { *color_mut = color; if index == self.led_colors.len() - 1 { self.sync().await?; } } } _ => {} }, message::SetArg::Priority(priority) => { self.set_priority(priority).await; } } Ok(None) } BoblightRequest::Sync => { self.sync().await?; Ok(None) } } } } impl std::fmt::Debug for ClientConnection { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ClientConnection") .field("instance", &self.instance.id()) .field("source", &format!("{}", &*self.handle)) .finish() } }
handle, priority_guard, led_colors: vec![Color::default(); led_count], priority: 128, instance, } }
function_block-function_prefixed
[ { "content": "fn error_response(peer_addr: SocketAddr, error: impl std::fmt::Display) -> message::HyperionReply {\n\n let mut reply = message::HyperionReply::default();\n\n reply.r#type = message::hyperion_reply::Type::Reply.into();\n\n reply.success = Some(false);\n\n reply.error = Some(error.to_st...
Rust
src/proxy/sessions/session_manager.rs
iffyio/quilkin
d5e1024b057c7de11e403c2e942ce51b25ae846d
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::collections::HashMap; use std::sync::Arc; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use slog::{debug, warn, Logger}; use tokio::sync::{watch, RwLock, RwLockReadGuard, RwLockWriteGuard}; use crate::proxy::sessions::{Session, SessionKey}; type SessionsMap = HashMap<SessionKey, Session>; type Sessions = Arc<RwLock<SessionsMap>>; pub const SESSION_TIMEOUT_SECONDS: u64 = 60; const SESSION_EXPIRY_POLL_INTERVAL: u64 = 60; #[derive(Clone)] pub struct SessionManager(Sessions); impl SessionManager { pub fn new(log: Logger, shutdown_rx: watch::Receiver<()>) -> Self { let poll_interval = Duration::from_secs(SESSION_EXPIRY_POLL_INTERVAL); let sessions: Sessions = Arc::new(RwLock::new(HashMap::new())); Self::run_prune_sessions(log.clone(), sessions.clone(), poll_interval, shutdown_rx); Self(sessions) } pub async fn get_sessions(&self) -> RwLockReadGuard<'_, SessionsMap> { self.0.read().await } pub async fn get_sessions_mut(&self) -> RwLockWriteGuard<'_, SessionsMap> { self.0.write().await } fn run_prune_sessions( log: Logger, mut sessions: Sessions, poll_interval: Duration, mut shutdown_rx: watch::Receiver<()>, ) { let mut interval = tokio::time::interval(poll_interval); tokio::spawn(async move { loop { tokio::select! { _ = shutdown_rx.changed() => { debug!(log, "Exiting Prune Sessions due to shutdown signal."); break; } _ = interval.tick() => { debug!(log, "Attempting to Prune Sessions"); Self::prune_sessions(&log, &mut sessions).await; } } } }); } async fn prune_sessions(log: &Logger, sessions: &mut Sessions) { let now = if let Ok(now) = SystemTime::now().duration_since(UNIX_EPOCH) { now.as_secs() } else { warn!(log, "Failed to get current time when pruning sessions"); return; }; let expired_keys = (*sessions.read().await) .iter() .filter(|(_, session)| session.expiration() <= now) .count(); if expired_keys != 0 { sessions .write() .await .retain(|_, session| session.expiration() > now); } } } #[cfg(test)] mod tests { use std::collections::HashMap; use std::net::SocketAddr; use std::ops::Add; use std::sync::Arc; use std::time::Duration; use prometheus::Registry; use tokio::sync::{mpsc, watch, RwLock}; use crate::cluster::Endpoint; use crate::filters::{manager::FilterManager, FilterChain}; use crate::proxy::sessions::metrics::Metrics; use crate::proxy::sessions::session_manager::Sessions; use crate::proxy::sessions::{Packet, Session, SessionKey}; use crate::test_utils::TestHelper; use super::SessionManager; #[tokio::test] async fn run_prune_sessions() { let t = TestHelper::default(); let sessions = Arc::new(RwLock::new(HashMap::new())); let from: SocketAddr = "127.0.0.1:7000".parse().unwrap(); let to: SocketAddr = "127.0.0.1:7001".parse().unwrap(); let (send, _recv) = mpsc::channel::<Packet>(1); let (_shutdown_tx, shutdown_rx) = watch::channel(()); let endpoint = Endpoint::from_address(to); let ttl = Duration::from_secs(1); let poll_interval = Duration::from_millis(1); SessionManager::run_prune_sessions( t.log.clone(), sessions.clone(), poll_interval, shutdown_rx, ); let key = SessionKey::from((from, to)); { let registry = Registry::default(); let mut sessions = sessions.write().await; sessions.insert( key.clone(), Session::new( &t.log, Metrics::new(&registry).unwrap(), FilterManager::fixed(Arc::new(FilterChain::new(vec![], &registry).unwrap())), from, endpoint.clone(), send, ttl, ) .await .unwrap(), ); } { let map = sessions.read().await; assert!(map.contains_key(&key)); assert_eq!(1, map.len()); } tokio::time::sleep_until(tokio::time::Instant::now().add(ttl)).await; for _ in 1..10000 { tokio::time::sleep(Duration::from_millis(1)).await; let map = sessions.read().await; if !map.contains_key(&key) && map.len() == 0 { break; } } { let map = sessions.read().await; assert!( !map.contains_key(&key), "should not contain the key after prune" ); assert_eq!(0, map.len(), "len should be 0, bit is {}", map.len()); } } #[tokio::test] async fn prune_sessions() { let t = TestHelper::default(); let mut sessions: Sessions = Arc::new(RwLock::new(HashMap::new())); let from: SocketAddr = "127.0.0.1:7000".parse().unwrap(); let to: SocketAddr = "127.0.0.1:7001".parse().unwrap(); let (send, _recv) = mpsc::channel::<Packet>(1); let endpoint = Endpoint::from_address(to); let key = SessionKey::from((from, to)); let ttl = Duration::from_secs(1); { let registry = Registry::default(); let mut sessions = sessions.write().await; sessions.insert( key.clone(), Session::new( &t.log, Metrics::new(&registry).unwrap(), FilterManager::fixed(Arc::new(FilterChain::new(vec![], &registry).unwrap())), from, endpoint.clone(), send, ttl, ) .await .unwrap(), ); } { let map = sessions.read().await; assert!(map.contains_key(&key)); assert_eq!(1, map.len()); } SessionManager::prune_sessions(&t.log, &mut sessions).await; { let map = sessions.read().await; assert!(map.contains_key(&key)); assert_eq!(1, map.len()); } tokio::time::sleep_until(tokio::time::Instant::now().add(ttl)).await; SessionManager::prune_sessions(&t.log, &mut sessions).await; { let map = sessions.read().await; assert!( !map.contains_key(&key), "should not contain the key after prune" ); assert_eq!(0, map.len(), "len should be 0, bit is {}", map.len()); } } }
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this
p.len()); } } }
file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::collections::HashMap; use std::sync::Arc; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use slog::{debug, warn, Logger}; use tokio::sync::{watch, RwLock, RwLockReadGuard, RwLockWriteGuard}; use crate::proxy::sessions::{Session, SessionKey}; type SessionsMap = HashMap<SessionKey, Session>; type Sessions = Arc<RwLock<SessionsMap>>; pub const SESSION_TIMEOUT_SECONDS: u64 = 60; const SESSION_EXPIRY_POLL_INTERVAL: u64 = 60; #[derive(Clone)] pub struct SessionManager(Sessions); impl SessionManager { pub fn new(log: Logger, shutdown_rx: watch::Receiver<()>) -> Self { let poll_interval = Duration::from_secs(SESSION_EXPIRY_POLL_INTERVAL); let sessions: Sessions = Arc::new(RwLock::new(HashMap::new())); Self::run_prune_sessions(log.clone(), sessions.clone(), poll_interval, shutdown_rx); Self(sessions) } pub async fn get_sessions(&self) -> RwLockReadGuard<'_, SessionsMap> { self.0.read().await } pub async fn get_sessions_mut(&self) -> RwLockWriteGuard<'_, SessionsMap> { self.0.write().await } fn run_prune_sessions( log: Logger, mut sessions: Sessions, poll_interval: Duration, mut shutdown_rx: watch::Receiver<()>, ) { let mut interval = tokio::time::interval(poll_interval); tokio::spawn(async move { loop { tokio::select! { _ = shutdown_rx.changed() => { debug!(log, "Exiting Prune Sessions due to shutdown signal."); break; } _ = interval.tick() => { debug!(log, "Attempting to Prune Sessions"); Self::prune_sessions(&log, &mut sessions).await; } } } }); } async fn prune_sessions(log: &Logger, sessions: &mut Sessions) { let now = if let Ok(now) = SystemTime::now().duration_since(UNIX_EPOCH) { now.as_secs() } else { warn!(log, "Failed to get current time when pruning sessions"); return; }; let expired_keys = (*sessions.read().await) .iter() .filter(|(_, session)| session.expiration() <= now) .count(); if expired_keys != 0 { sessions .write() .await .retain(|_, session| session.expiration() > now); } } } #[cfg(test)] mod tests { use std::collections::HashMap; use std::net::SocketAddr; use std::ops::Add; use std::sync::Arc; use std::time::Duration; use prometheus::Registry; use tokio::sync::{mpsc, watch, RwLock}; use crate::cluster::Endpoint; use crate::filters::{manager::FilterManager, FilterChain}; use crate::proxy::sessions::metrics::Metrics; use crate::proxy::sessions::session_manager::Sessions; use crate::proxy::sessions::{Packet, Session, SessionKey}; use crate::test_utils::TestHelper; use super::SessionManager; #[tokio::test] async fn run_prune_sessions() { let t = TestHelper::default(); let sessions = Arc::new(RwLock::new(HashMap::new())); let from: SocketAddr = "127.0.0.1:7000".parse().unwrap(); let to: SocketAddr = "127.0.0.1:7001".parse().unwrap(); let (send, _recv) = mpsc::channel::<Packet>(1); let (_shutdown_tx, shutdown_rx) = watch::channel(()); let endpoint = Endpoint::from_address(to); let ttl = Duration::from_secs(1); let poll_interval = Duration::from_millis(1); SessionManager::run_prune_sessions( t.log.clone(), sessions.clone(), poll_interval, shutdown_rx, ); let key = SessionKey::from((from, to)); { let registry = Registry::default(); let mut sessions = sessions.write().await; sessions.insert( key.clone(), Session::new( &t.log, Metrics::new(&registry).unwrap(), FilterManager::fixed(Arc::new(FilterChain::new(vec![], &registry).unwrap())), from, endpoint.clone(), send, ttl, ) .await .unwrap(), ); } { let map = sessions.read().await; assert!(map.contains_key(&key)); assert_eq!(1, map.len()); } tokio::time::sleep_until(tokio::time::Instant::now().add(ttl)).await; for _ in 1..10000 { tokio::time::sleep(Duration::from_millis(1)).await; let map = sessions.read().await; if !map.contains_key(&key) && map.len() == 0 { break; } } { let map = sessions.read().await; assert!( !map.contains_key(&key), "should not contain the key after prune" ); assert_eq!(0, map.len(), "len should be 0, bit is {}", map.len()); } } #[tokio::test] async fn prune_sessions() { let t = TestHelper::default(); let mut sessions: Sessions = Arc::new(RwLock::new(HashMap::new())); let from: SocketAddr = "127.0.0.1:7000".parse().unwrap(); let to: SocketAddr = "127.0.0.1:7001".parse().unwrap(); let (send, _recv) = mpsc::channel::<Packet>(1); let endpoint = Endpoint::from_address(to); let key = SessionKey::from((from, to)); let ttl = Duration::from_secs(1); { let registry = Registry::default(); let mut sessions = sessions.write().await; sessions.insert( key.clone(), Session::new( &t.log, Metrics::new(&registry).unwrap(), FilterManager::fixed(Arc::new(FilterChain::new(vec![], &registry).unwrap())), from, endpoint.clone(), send, ttl, ) .await .unwrap(), ); } { let map = sessions.read().await; assert!(map.contains_key(&key)); assert_eq!(1, map.len()); } SessionManager::prune_sessions(&t.log, &mut sessions).await; { let map = sessions.read().await; assert!(map.contains_key(&key)); assert_eq!(1, map.len()); } tokio::time::sleep_until(tokio::time::Instant::now().add(ttl)).await; SessionManager::prune_sessions(&t.log, &mut sessions).await; { let map = sessions.read().await; assert!( !map.contains_key(&key), "should not contain the key after prune" ); assert_eq!(0, map.len(), "len should be 0, bit is {}", ma
random
[ { "content": "# Using Quilkin\n\n\n\nThere are two choices for running Quilkin:\n\n\n\n* Binary\n\n* Container image\n\n\n\nFor each version there is both a release version, which is optimised for production usage, and a debug version that \n\nhas debug level logging enabled.\n\n\n\n## Binary\n\n\n\nThe release...
Rust
nanocurrency-peering/src/lib.rs
tundak/railroad
b18298aab4ad72b045227a94162d9cd1a510ef51
use std::iter::IntoIterator; use std::io; use std::net::{SocketAddr, SocketAddrV6, ToSocketAddrs}; use std::cell::RefCell; use std::rc::Rc; use std::time::{Duration, Instant}; use std::collections::{hash_map, HashMap}; use std::marker::PhantomData; use std::fmt::Debug; #[macro_use] extern crate log; #[macro_use] extern crate futures; use futures::{stream, Future, Sink, Stream}; extern crate net2; use net2::UdpBuilder; extern crate bytes; extern crate tokio; use tokio::net::UdpSocket; use tokio::reactor::Handle; extern crate tokio_io; extern crate tokio_timer; use tokio_timer::Timer; extern crate rand; use rand::{thread_rng, Rng}; extern crate nanocurrency_protocol; use nanocurrency_protocol::*; #[macro_use] extern crate nanocurrency_types; use nanocurrency_types::Network; mod udp_framed; const KEEPALIVE_INTERVAL: u64 = 60; const KEEPALIVE_CUTOFF: u64 = KEEPALIVE_INTERVAL * 5; pub fn addr_to_ipv6(addr: SocketAddr) -> SocketAddrV6 { match addr { SocketAddr::V4(addr) => SocketAddrV6::new(addr.ip().to_ipv6_mapped(), addr.port(), 0, 0), SocketAddr::V6(addr) => addr, } } struct IgnoreErrors<S: Stream, E> where S::Error: Debug, { inner: S, err_phantom: PhantomData<E>, } impl<S: Stream, E: Debug> Stream for IgnoreErrors<S, E> where S::Error: Debug, { type Item = S::Item; type Error = E; fn poll(&mut self) -> Result<futures::Async<Option<S::Item>>, E> { loop { match self.inner.poll() { Ok(x) => return Ok(x), Err(err) => debug!("ignoring error: {:?}", err), } } } } fn ignore_errors<S: Stream, E>(stream: S) -> IgnoreErrors<S, E> where S::Error: Debug, { IgnoreErrors { inner: stream, err_phantom: PhantomData, } } pub struct PeerInfo { pub last_heard_from: Instant, pub network_version: u8, _private: (), } #[derive(Default)] pub struct PeeringManagerState { peers: HashMap<SocketAddrV6, PeerInfo>, rand_peers: RefCell<Vec<SocketAddrV6>>, new_peer_backoff: HashMap<SocketAddrV6, Instant>, } impl PeeringManagerState { pub fn get_rand_peers(&self, peers_out: &mut [SocketAddrV6]) { if self.peers.len() < peers_out.len() { for (peer, peer_out) in self.peers.keys().zip(peers_out.iter_mut()) { *peer_out = *peer; } return; } let mut thread_rng = thread_rng(); let mut rand_peers = self.rand_peers.borrow_mut(); for peer_out in peers_out.iter_mut() { if rand_peers.is_empty() { rand_peers.extend(self.peers.keys()); thread_rng.shuffle(&mut rand_peers); } *peer_out = rand_peers.pop().unwrap(); } } pub fn peers(&self) -> &HashMap<SocketAddrV6, PeerInfo> { &self.peers } fn contacted(&mut self, addr: SocketAddr, header: &MessageHeader) { let addr = addr_to_ipv6(addr); match self.peers.entry(addr) { hash_map::Entry::Occupied(mut entry) => { entry.get_mut().last_heard_from = Instant::now(); } hash_map::Entry::Vacant(entry) => { entry.insert(PeerInfo { last_heard_from: Instant::now(), network_version: header.version, _private: (), }); } } } } pub struct PeeringManagerBuilder<F, I, II> where I: Iterator<Item = (Message, SocketAddr)>, II: IntoIterator<Item = (Message, SocketAddr), IntoIter = I>, F: Fn(&PeeringManagerState, MessageHeader, Message, SocketAddr) -> II + 'static, { use_official_peers: bool, custom_peers: Vec<SocketAddr>, listen_addr: SocketAddr, network: Network, message_handler: F, state_base: Rc<RefCell<PeeringManagerState>>, send_messages: Box<Stream<Item = (Message, SocketAddr), Error = ()>>, } impl<F, I, II> PeeringManagerBuilder<F, I, II> where I: Iterator<Item = (Message, SocketAddr)>, II: IntoIterator<Item = (Message, SocketAddr), IntoIter = I>, F: Fn(&PeeringManagerState, MessageHeader, Message, SocketAddr) -> II + 'static, { pub fn new(message_handler: F) -> PeeringManagerBuilder<F, I, II> { PeeringManagerBuilder { use_official_peers: true, custom_peers: Vec::new(), listen_addr: "[::]:7075".parse().unwrap(), network: Network::Live, message_handler, state_base: Default::default(), send_messages: Box::new(stream::empty()), } } pub fn use_official_peers(mut self, value: bool) -> Self { self.use_official_peers = value; self } pub fn custom_peers(mut self, value: Vec<SocketAddr>) -> Self { self.custom_peers = value; self } pub fn listen_addr(mut self, value: SocketAddr) -> Self { self.listen_addr = value; self } pub fn network(mut self, value: Network) -> Self { self.network = value; self } pub fn state_base(mut self, value: Rc<RefCell<PeeringManagerState>>) -> Self { self.state_base = value; self } pub fn send_messages( mut self, value: Box<Stream<Item = (Message, SocketAddr), Error = ()>>, ) -> Self { self.send_messages = value; self } pub fn run(self) -> io::Result<Box<Future<Item = (), Error = ()>>> { let mut configured_peers: Vec<SocketAddrV6> = Vec::new(); if self.use_official_peers { let official_domain = match self.network { Network::Live => Some("rai.raiblocks.net:7075"), Network::Beta => Some("rai-beta.raiblocks.net:7075"), Network::Test => None, }; if let Some(official_domain) = official_domain { configured_peers.extend(official_domain.to_socket_addrs()?.map(addr_to_ipv6)); } } configured_peers.extend(self.custom_peers.into_iter().map(addr_to_ipv6)); let socket; if cfg!(target_os = "windows") { let std_socket = UdpBuilder::new_v6()? .only_v6(false)? .bind(self.listen_addr)?; socket = UdpSocket::from_std(std_socket, &Handle::current())?; } else { socket = UdpSocket::bind(&self.listen_addr)?; } let (sink, stream) = udp_framed::UdpFramed::new(socket, NanoCurrencyCodec).split(); let network = self.network; let message_handler = self.message_handler; let state_rc = self.state_base.clone(); let process_message = move |((header, msg), src)| { let _: &MessageHeader = &header; if header.network != network { warn!("ignoring message from {:?} network", header.network); return stream::iter_ok(Vec::new().into_iter()); } let mut state = state_rc.borrow_mut(); state.contacted(src, &header); trace!("got message from {:?}: {:?}", src, msg); let mut output_messages = Vec::new(); match msg { Message::Keepalive(new_peers) => { let state = &mut state; output_messages.extend(new_peers.to_vec().into_iter().filter_map( move |new_peer| { match state.new_peer_backoff.entry(new_peer) { hash_map::Entry::Occupied(mut entry) => { let entry = entry.get_mut(); if *entry > Instant::now() - Duration::from_secs(KEEPALIVE_CUTOFF) { return None; } *entry = Instant::now(); } hash_map::Entry::Vacant(entry) => { entry.insert(Instant::now()); } } if state.peers.contains_key(&new_peer) { return None; } let ip = new_peer.ip().clone(); if ip.octets().iter().all(|&x| x == 0) { return None; } if new_peer.port() == 0 { return None; } if ip.is_unspecified() || ip.is_loopback() || ip.is_multicast() { return None; } let mut rand_peers = [zero_v6_addr!(); 8]; state.get_rand_peers(&mut rand_peers); Some(( (network, Message::Keepalive(rand_peers)), SocketAddr::V6(new_peer), )) }, )); } _ => {} } output_messages.extend( (message_handler)(&state, header, msg, src) .into_iter() .map(|(m, a)| ((network, m), a)), ); stream::iter_ok::<_, io::Error>(output_messages) }; let process_messages = stream.map(process_message).flatten(); let state_rc = self.state_base.clone(); let timer = Timer::default(); let keepalive = stream::once(Ok(())) .chain(timer.interval(Duration::from_secs(KEEPALIVE_INTERVAL))) .map(move |_| { let mut state = state_rc.borrow_mut(); let last_heard_cutoff = Instant::now() - Duration::from_secs(KEEPALIVE_CUTOFF); state .new_peer_backoff .retain(|_, ts| *ts > last_heard_cutoff); state .peers .retain(|_, info| info.last_heard_from > last_heard_cutoff); debug!("peers: {:?}", state.peers.keys()); let mut keepalives = Vec::with_capacity(state.peers.len()); for addr in state .peers .iter() .map(|(a, _)| a) .chain(configured_peers.iter()) { let mut rand_peers = [zero_v6_addr!(); 8]; state.get_rand_peers(&mut rand_peers); keepalives.push(( (network, Message::Keepalive(rand_peers)), SocketAddr::V6(*addr), )); } stream::iter_ok::<_, io::Error>(keepalives.into_iter()) }) .flatten(); let send_messages = self.send_messages.map(move |(msg, addr)| ((network, msg), addr)); Ok(Box::new( sink.send_all( ignore_errors::<_, io::Error>(process_messages) .select(ignore_errors(keepalive)) .select(ignore_errors(send_messages)), ).map(|_| ()) .map_err(|_| ()), )) } }
use std::iter::IntoIterator; use std::io; use std::net::{SocketAddr, SocketAddrV6, ToSocketAddrs}; use std::cell::RefCell; use std::rc::Rc; use std::time::{Duration, Instant}; use std::collections::{hash_map, HashMap}; use std::marker::PhantomData; use std::fmt::Debug; #[macro_use] extern crate log; #[macro_use] extern crate futures; use futures::{stream, Future, Sink, Stream}; extern crate net2; use net2::UdpBuilder; extern crate bytes; extern crate tokio; use tokio::net::UdpSocket; use tokio::reactor::Handle; extern crate tokio_io; extern crate tokio_timer; use tokio_timer::Timer; extern crate rand; use rand::{thread_rng, Rng}; extern crate nanocurrency_protocol; use nanocurrency_protocol::*; #[macro_use] extern crate nanocurrency_types; use nanocurrency_types::Network; mod udp_frame
hash_map::Entry::Vacant(entry) => { entry.insert(Instant::now()); } } if state.peers.contains_key(&new_peer) { return None; } let ip = new_peer.ip().clone(); if ip.octets().iter().all(|&x| x == 0) { return None; } if new_peer.port() == 0 { return None; } if ip.is_unspecified() || ip.is_loopback() || ip.is_multicast() { return None; } let mut rand_peers = [zero_v6_addr!(); 8]; state.get_rand_peers(&mut rand_peers); Some(( (network, Message::Keepalive(rand_peers)), SocketAddr::V6(new_peer), )) }, )); } _ => {} } output_messages.extend( (message_handler)(&state, header, msg, src) .into_iter() .map(|(m, a)| ((network, m), a)), ); stream::iter_ok::<_, io::Error>(output_messages) }; let process_messages = stream.map(process_message).flatten(); let state_rc = self.state_base.clone(); let timer = Timer::default(); let keepalive = stream::once(Ok(())) .chain(timer.interval(Duration::from_secs(KEEPALIVE_INTERVAL))) .map(move |_| { let mut state = state_rc.borrow_mut(); let last_heard_cutoff = Instant::now() - Duration::from_secs(KEEPALIVE_CUTOFF); state .new_peer_backoff .retain(|_, ts| *ts > last_heard_cutoff); state .peers .retain(|_, info| info.last_heard_from > last_heard_cutoff); debug!("peers: {:?}", state.peers.keys()); let mut keepalives = Vec::with_capacity(state.peers.len()); for addr in state .peers .iter() .map(|(a, _)| a) .chain(configured_peers.iter()) { let mut rand_peers = [zero_v6_addr!(); 8]; state.get_rand_peers(&mut rand_peers); keepalives.push(( (network, Message::Keepalive(rand_peers)), SocketAddr::V6(*addr), )); } stream::iter_ok::<_, io::Error>(keepalives.into_iter()) }) .flatten(); let send_messages = self.send_messages.map(move |(msg, addr)| ((network, msg), addr)); Ok(Box::new( sink.send_all( ignore_errors::<_, io::Error>(process_messages) .select(ignore_errors(keepalive)) .select(ignore_errors(send_messages)), ).map(|_| ()) .map_err(|_| ()), )) } }
d; const KEEPALIVE_INTERVAL: u64 = 60; const KEEPALIVE_CUTOFF: u64 = KEEPALIVE_INTERVAL * 5; pub fn addr_to_ipv6(addr: SocketAddr) -> SocketAddrV6 { match addr { SocketAddr::V4(addr) => SocketAddrV6::new(addr.ip().to_ipv6_mapped(), addr.port(), 0, 0), SocketAddr::V6(addr) => addr, } } struct IgnoreErrors<S: Stream, E> where S::Error: Debug, { inner: S, err_phantom: PhantomData<E>, } impl<S: Stream, E: Debug> Stream for IgnoreErrors<S, E> where S::Error: Debug, { type Item = S::Item; type Error = E; fn poll(&mut self) -> Result<futures::Async<Option<S::Item>>, E> { loop { match self.inner.poll() { Ok(x) => return Ok(x), Err(err) => debug!("ignoring error: {:?}", err), } } } } fn ignore_errors<S: Stream, E>(stream: S) -> IgnoreErrors<S, E> where S::Error: Debug, { IgnoreErrors { inner: stream, err_phantom: PhantomData, } } pub struct PeerInfo { pub last_heard_from: Instant, pub network_version: u8, _private: (), } #[derive(Default)] pub struct PeeringManagerState { peers: HashMap<SocketAddrV6, PeerInfo>, rand_peers: RefCell<Vec<SocketAddrV6>>, new_peer_backoff: HashMap<SocketAddrV6, Instant>, } impl PeeringManagerState { pub fn get_rand_peers(&self, peers_out: &mut [SocketAddrV6]) { if self.peers.len() < peers_out.len() { for (peer, peer_out) in self.peers.keys().zip(peers_out.iter_mut()) { *peer_out = *peer; } return; } let mut thread_rng = thread_rng(); let mut rand_peers = self.rand_peers.borrow_mut(); for peer_out in peers_out.iter_mut() { if rand_peers.is_empty() { rand_peers.extend(self.peers.keys()); thread_rng.shuffle(&mut rand_peers); } *peer_out = rand_peers.pop().unwrap(); } } pub fn peers(&self) -> &HashMap<SocketAddrV6, PeerInfo> { &self.peers } fn contacted(&mut self, addr: SocketAddr, header: &MessageHeader) { let addr = addr_to_ipv6(addr); match self.peers.entry(addr) { hash_map::Entry::Occupied(mut entry) => { entry.get_mut().last_heard_from = Instant::now(); } hash_map::Entry::Vacant(entry) => { entry.insert(PeerInfo { last_heard_from: Instant::now(), network_version: header.version, _private: (), }); } } } } pub struct PeeringManagerBuilder<F, I, II> where I: Iterator<Item = (Message, SocketAddr)>, II: IntoIterator<Item = (Message, SocketAddr), IntoIter = I>, F: Fn(&PeeringManagerState, MessageHeader, Message, SocketAddr) -> II + 'static, { use_official_peers: bool, custom_peers: Vec<SocketAddr>, listen_addr: SocketAddr, network: Network, message_handler: F, state_base: Rc<RefCell<PeeringManagerState>>, send_messages: Box<Stream<Item = (Message, SocketAddr), Error = ()>>, } impl<F, I, II> PeeringManagerBuilder<F, I, II> where I: Iterator<Item = (Message, SocketAddr)>, II: IntoIterator<Item = (Message, SocketAddr), IntoIter = I>, F: Fn(&PeeringManagerState, MessageHeader, Message, SocketAddr) -> II + 'static, { pub fn new(message_handler: F) -> PeeringManagerBuilder<F, I, II> { PeeringManagerBuilder { use_official_peers: true, custom_peers: Vec::new(), listen_addr: "[::]:7075".parse().unwrap(), network: Network::Live, message_handler, state_base: Default::default(), send_messages: Box::new(stream::empty()), } } pub fn use_official_peers(mut self, value: bool) -> Self { self.use_official_peers = value; self } pub fn custom_peers(mut self, value: Vec<SocketAddr>) -> Self { self.custom_peers = value; self } pub fn listen_addr(mut self, value: SocketAddr) -> Self { self.listen_addr = value; self } pub fn network(mut self, value: Network) -> Self { self.network = value; self } pub fn state_base(mut self, value: Rc<RefCell<PeeringManagerState>>) -> Self { self.state_base = value; self } pub fn send_messages( mut self, value: Box<Stream<Item = (Message, SocketAddr), Error = ()>>, ) -> Self { self.send_messages = value; self } pub fn run(self) -> io::Result<Box<Future<Item = (), Error = ()>>> { let mut configured_peers: Vec<SocketAddrV6> = Vec::new(); if self.use_official_peers { let official_domain = match self.network { Network::Live => Some("rai.raiblocks.net:7075"), Network::Beta => Some("rai-beta.raiblocks.net:7075"), Network::Test => None, }; if let Some(official_domain) = official_domain { configured_peers.extend(official_domain.to_socket_addrs()?.map(addr_to_ipv6)); } } configured_peers.extend(self.custom_peers.into_iter().map(addr_to_ipv6)); let socket; if cfg!(target_os = "windows") { let std_socket = UdpBuilder::new_v6()? .only_v6(false)? .bind(self.listen_addr)?; socket = UdpSocket::from_std(std_socket, &Handle::current())?; } else { socket = UdpSocket::bind(&self.listen_addr)?; } let (sink, stream) = udp_framed::UdpFramed::new(socket, NanoCurrencyCodec).split(); let network = self.network; let message_handler = self.message_handler; let state_rc = self.state_base.clone(); let process_message = move |((header, msg), src)| { let _: &MessageHeader = &header; if header.network != network { warn!("ignoring message from {:?} network", header.network); return stream::iter_ok(Vec::new().into_iter()); } let mut state = state_rc.borrow_mut(); state.contacted(src, &header); trace!("got message from {:?}: {:?}", src, msg); let mut output_messages = Vec::new(); match msg { Message::Keepalive(new_peers) => { let state = &mut state; output_messages.extend(new_peers.to_vec().into_iter().filter_map( move |new_peer| { match state.new_peer_backoff.entry(new_peer) { hash_map::Entry::Occupied(mut entry) => { let entry = entry.get_mut(); if *entry > Instant::now() - Duration::from_secs(KEEPALIVE_CUTOFF) { return None; } *entry = Instant::now(); }
random
[ { "content": "mod serde;\n", "file_path": "nanocurrency-types/src/tests/mod.rs", "rank": 2, "score": 26395.1323353986 }, { "content": "mod udp_encode_decode;\n", "file_path": "nanocurrency-protocol/src/tests/mod.rs", "rank": 3, "score": 26394.98531009027 }, { "content": "...
Rust
fltk-derive/src/group.rs
andrrff/fltk-rs
1db0fd4c2341b005cd949ac6a3a7b8ab949ada6c
use crate::utils::get_fl_name; use proc_macro::TokenStream; use quote::*; use syn::*; pub fn impl_group_trait(ast: &DeriveInput) -> TokenStream { let name = &ast.ident; let name_str = get_fl_name(name.to_string()); let begin = Ident::new(format!("{}_{}", name_str, "begin").as_str(), name.span()); let end = Ident::new(format!("{}_{}", name_str, "end").as_str(), name.span()); let clear = Ident::new(format!("{}_{}", name_str, "clear").as_str(), name.span()); let children = Ident::new(format!("{}_{}", name_str, "children").as_str(), name.span()); let child = Ident::new(format!("{}_{}", name_str, "child").as_str(), name.span()); let find = Ident::new(format!("{}_{}", name_str, "find").as_str(), name.span()); let add = Ident::new(format!("{}_{}", name_str, "add").as_str(), name.span()); let insert = Ident::new(format!("{}_{}", name_str, "insert").as_str(), name.span()); let remove = Ident::new(format!("{}_{}", name_str, "remove").as_str(), name.span()); let remove_by_index = Ident::new( format!("{}_{}", name_str, "remove_by_index").as_str(), name.span(), ); let resizable = Ident::new( format!("{}_{}", name_str, "resizable").as_str(), name.span(), ); let clip_children = Ident::new( format!("{}_{}", name_str, "clip_children").as_str(), name.span(), ); let set_clip_children = Ident::new( format!("{}_{}", name_str, "set_clip_children").as_str(), name.span(), ); let init_sizes = Ident::new( format!("{}_{}", name_str, "init_sizes").as_str(), name.span(), ); let gen = quote! { impl IntoIterator for #name { type Item = Widget; type IntoIter = std::vec::IntoIter<Self::Item>; fn into_iter(self) -> Self::IntoIter { let mut v: Vec<Widget> = vec![]; for i in 0..self.children() { v.push(self.child(i).unwrap()); } v.into_iter() } } unsafe impl GroupExt for #name { fn begin(&self) { assert!(!self.was_deleted()); unsafe { #begin(self.inner) } } fn end(&self) { assert!(!self.was_deleted()); unsafe { #end(self.inner) } } fn clear(&mut self) { assert!(!self.was_deleted()); unsafe { #clear(self.inner); } } unsafe fn unsafe_clear(&mut self) { assert!(!self.was_deleted()); unsafe { #clear(self.inner); } } fn children(&self) -> i32 { unsafe { assert!(!self.was_deleted()); #children(self.inner) as i32 } } fn child(&self, idx: i32) -> Option<Widget> { unsafe { assert!(!self.was_deleted()); if idx >= self.children() || idx < 0 { return None; } let child_widget = #child(self.inner, idx as i32); if child_widget.is_null() { None } else { Some(Widget::from_widget_ptr(child_widget as *mut fltk_sys::widget::Fl_Widget)) } } } fn find<W: WidgetExt>(&self, widget: &W) -> i32 { unsafe { assert!(!self.was_deleted()); assert!(!widget.was_deleted()); #find(self.inner, widget.as_widget_ptr() as *mut _) as i32 } } fn add<W: WidgetExt>(&mut self, widget: &W) { unsafe { assert!(!self.was_deleted()); assert!(!widget.was_deleted()); #add(self.inner, widget.as_widget_ptr() as *mut _) } } fn insert<W: WidgetExt>(&mut self, widget: &W, index: i32) { unsafe { assert!(!self.was_deleted()); assert!(!widget.was_deleted()); #insert(self.inner, widget.as_widget_ptr() as *mut _, index as i32) } } fn remove<W: WidgetExt>(&mut self, widget: &W) { unsafe { assert!(!self.was_deleted()); assert!(!widget.was_deleted()); #remove(self.inner, widget.as_widget_ptr() as *mut _) } } fn remove_by_index(&mut self, idx: i32) { unsafe { assert!(!self.was_deleted()); assert!(idx < self.children()); #remove_by_index(self.inner, idx as i32); } } fn resizable<W: WidgetExt>(&self, widget: &W) { unsafe { assert!(!self.was_deleted()); assert!(!widget.was_deleted()); #resizable(self.inner, widget.as_widget_ptr() as *mut _) } } fn make_resizable(&mut self, val: bool) { assert!(!self.was_deleted()); let ptr = if val { self.inner } else { std::ptr::null_mut() }; unsafe { #resizable(self.inner, ptr as *mut _) } } fn add_resizable<W: WidgetExt>(&mut self, widget: &W) { self.resizable(widget); self.add(widget); } fn set_clip_children(&mut self, flag: bool) { assert!(!self.was_deleted()); unsafe { #set_clip_children(self.inner, flag as i32) } } fn clip_children(&mut self) -> bool { assert!(!self.was_deleted()); unsafe { #clip_children(self.inner) != 0 } } fn draw_child<W: WidgetExt>(&self, w: &mut W) { assert!(!self.was_deleted()); assert!(!w.was_deleted()); unsafe { crate::app::open_display(); Fl_Group_draw_child(self.inner as _, w.as_widget_ptr() as _) } } fn update_child<W: WidgetExt>(&self, w: &mut W) { assert!(!self.was_deleted()); assert!(!w.was_deleted()); unsafe { crate::app::open_display(); Fl_Group_update_child(self.inner as _, w.as_widget_ptr() as _) } } fn draw_outside_label<W: WidgetExt>(&self, w: &mut W) { assert!(!self.was_deleted()); assert!(!w.was_deleted()); unsafe { crate::app::open_display(); Fl_Group_draw_outside_label(self.inner as _, w.as_widget_ptr() as _) } } fn draw_children(&mut self) { assert!(!self.was_deleted()); unsafe { crate::app::open_display(); Fl_Group_draw_children(self.inner as _) } } fn init_sizes(&mut self) { unsafe { assert!(!self.was_deleted()); #init_sizes(self.inner) } } fn bounds(&self) -> Vec<(i32, i32, i32, i32)> { let children = self.children(); let mut vec = vec![]; for i in 0..children { let child = self.child(i).unwrap(); let x = child.x(); let y = child.y(); let r = child.w() + x; let b = child.h() + y; vec.push((x, y, r, b)); } vec } unsafe fn into_group(&self) -> crate::group::Group { crate::group::Group::from_widget_ptr(self.inner as _) } } }; gen.into() }
use crate::utils::get_fl_name; use proc_macro::TokenStream; use quote::*; use syn::*; pub fn impl_group_trait(ast: &DeriveInput) -> TokenStream { let name = &ast.ident; let name_str = get_fl_name(name.to_string()); let begin = Ident::new(format!("{}_{}", name_str, "begin").as_str(), name.span()); let end = Ident::new(format!("{}_{}", name_str, "end").as_str(), name.span()); let clear = Ident::new(format!("{}_{}", name_str, "clear").as_str(), name.span()); let children = Ident::new(format!("{}_{}", name_str, "children").as_str(), name.span()); let child = Ident::new(format!("{}_{}", name_str, "child").as_str(), name.span()); let find = Ident::new(format!("{}_{}", name_str, "find").as_str(), name.span()); let add = Ident::new(format!("{}_{}", name_str, "add").as_str(), name.span()); let insert = Ident::new(format!("{}_{}", name_str, "insert").as_str(), name.span()); let remove = Ident::new(format!("{}_{}", name_str, "remove").as_str(), name.span()); let remove_by_index = Ident::new( format!("{}_{}", name_str, "remove_by_index").as_str(), name.span(), ); let resizable = Ident::new( format!("{}_{}", name_str, "resizable").as_str(), name.span(), ); let clip_children = Ident::new( format!("{}_{}", name_str, "clip_children").as_str(), name.span(), ); let set_clip_children = Ident::new( format!("{}_{}", name_str, "set_clip_children").as_str(), name.span(), ); let init_sizes = Ident::new( format!("{}_{}", name_str, "init_sizes").as_str(), name.span(), ); let gen = quote! { impl IntoIterator for #name { type Item = Widget; type IntoIter = std::vec::IntoIter<Self::Item>; fn into_iter(self) -> Self::IntoIter { let mut v: Vec<Widget> = vec![]; for i in 0..self.children() { v.push(self.child(i).unwrap()); } v.into_iter() } } unsafe impl GroupExt for #name { fn begin(&self) { assert!(!self.was_deleted()); unsafe { #begin(self.inner) } } fn end(&self) { assert!(!self.was_deleted()); unsafe { #end(self.inner) } } fn clear(&mut self) { assert!(!self.was_deleted()); unsafe { #clear(self.inner); } } unsafe fn unsafe_clear(&mut self) { assert!(!self.was_deleted()); unsafe { #clear(self.inner); } } fn children(&self) -> i32 { unsafe { assert!(!self.was_deleted()); #children(self.inner) as i32 } } fn child(&self, idx: i32) -> Option<Widget> { unsafe { assert!(!self.was_deleted()); if idx >= self.children() || idx < 0 { return None; } let child_widget = #child(self.inner, idx as i32); if child_widget.is_null() { None } else { Some(Widget::from_widget_ptr(child_widget as *mut fltk_sys::widget::Fl_Widget)) } } } fn find<W: WidgetExt>(&self, widget: &W) -> i32 { unsafe { assert!(!self.was_deleted()); assert!(!widget.was_deleted()); #find(self.inner, widget.as_widget_ptr() as *mut _) as i32 } } fn add<W: WidgetExt>(&mut self, widget: &W) { unsafe { assert!(!self.was_deleted()); assert!(!widget.was_deleted()); #add(self.inner, widget.as_widget_ptr() as *mut _) } } fn insert<W: WidgetExt>(&mut self, widget: &W, index: i32) { unsafe { assert!(!self.was_deleted()); assert!(!widget.was_deleted()); #insert(self.inner, widget.as_widget_ptr() as *mut _, index as i32) } } fn remove<W: WidgetExt>(&mut self, widget: &W) { unsafe { assert!(!self.was_deleted()); assert!(!widget.was_deleted()); #remove(self.inner, widget.as_widget_ptr() as *mut _) } } fn remove_by_index(&mut self, idx: i32) { unsafe { assert!(!self.was_deleted()); assert!(idx < self.children()); #remove_by_index(self.inner, idx as i32); } } fn resizable<W: WidgetExt>(&self, widget: &W) { unsafe { assert!(!self.was_deleted()); assert!(!widget.was_deleted()); #resizable(self.inner, widget.as_widget_ptr() as *mut _) } } fn make_resizable(&mut self, val: bool) { assert!(!self.was_deleted()); let ptr = if val { self.inner } else { std::ptr::null_mut() }; unsafe { #resizable(self.inner, ptr as *mut _) } } fn add_resizable<W: WidgetExt>(&mut self, widget: &W) { self.resizable(widget); self.add(widget); } fn set_clip_children(&mut self, flag: bool) { assert!(!self.was_deleted()); unsafe { #set_clip_children(self.inner, flag as i32) } } fn clip_children(&mut self) -> bool { assert!(!self.was_deleted()); unsafe { #clip_children(self.inner) != 0 } } fn draw_child<W: WidgetExt>(&self, w: &mut W) { assert!(!self.was_deleted()); assert!(!w.was_deleted()); unsafe { crate::app::open_display(); Fl_Group_draw_child(self.inner as _, w.as_widget_ptr() as _) } } fn update_child<W: WidgetExt>(&self, w: &mut W) { assert!(!self.was_deleted()); assert!(!w.was_deleted()); unsafe { crate::app::open_display(); Fl_Group_update_child(self.inner as _, w.as_widget_ptr() as _) } } fn draw_outside_label<W: WidgetExt>(&self, w: &mut W) { assert!(!self.was_deleted()); assert!(!w.was_deleted());
unsafe { crate::app::open_display(); Fl_Group_draw_outside_label(self.inner as _, w.as_widget_ptr() as _) } } fn draw_children(&mut self) { assert!(!self.was_deleted()); unsafe { crate::app::open_display(); Fl_Group_draw_children(self.inner as _) } } fn init_sizes(&mut self) { unsafe { assert!(!self.was_deleted()); #init_sizes(self.inner) } } fn bounds(&self) -> Vec<(i32, i32, i32, i32)> { let children = self.children(); let mut vec = vec![]; for i in 0..children { let child = self.child(i).unwrap(); let x = child.x(); let y = child.y(); let r = child.w() + x; let b = child.h() + y; vec.push((x, y, r, b)); } vec } unsafe fn into_group(&self) -> crate::group::Group { crate::group::Group::from_widget_ptr(self.inner as _) } } }; gen.into() }
function_block-function_prefix_line
[ { "content": "/// Sets the callback of a widget\n\npub fn set_callback<F, W>(widget: &mut W, cb: F)\n\nwhere\n\n F: FnMut(&mut dyn WidgetExt),\n\n W: WidgetExt,\n\n{\n\n assert!(!widget.was_deleted());\n\n unsafe {\n\n unsafe extern \"C\" fn shim(wid: *mut fltk_sys::widget::Fl_Widget, data: *...
Rust
render_pi/src/gl_context.rs
j-selby/leaffront
13b15fda0ffa309433e08dc17d4bb0e3f20e9335
use egl; use egl::{EGLConfig, EGLContext, EGLDisplay, EGLNativeDisplayType, EGLSurface}; use videocore::bcm_host; use videocore::dispmanx; use videocore::dispmanx::{ DisplayHandle, ElementHandle, FlagsAlpha, Transform, UpdateHandle, VCAlpha, Window, }; use videocore::image::Rect; use videocore::bcm_host::GraphicsDisplaySize; use std::ptr; pub struct Context { pub config: EGLConfig, pub context: EGLContext, pub display: EGLDisplay, pub surface: EGLSurface, #[allow(dead_code)] window: Box<Window>, pub dispman_display: DisplayHandle, pub update: UpdateHandle, pub element: ElementHandle, pub bg_element: ElementHandle, } impl Context { pub fn get_resolution() -> GraphicsDisplaySize { bcm_host::graphics_get_display_size(0).unwrap() } pub fn swap_buffers(&self) -> bool { egl::swap_buffers(self.display, self.surface) } pub fn build() -> Result<Self, String> { bcm_host::init(); let display = dispmanx::display_open(0); let update = dispmanx::update_start(0); let dimensions: Result<GraphicsDisplaySize, String> = match bcm_host::graphics_get_display_size(0) { Some(x) => Ok(x), None => Err("bcm_host::init() did not succeed".into()), }; let dimensions = dimensions?; println!("Display size: {}x{}", dimensions.width, dimensions.height); let mut dest_rect = Rect { x: 0, y: 0, width: dimensions.width as i32, height: dimensions.height as i32, }; let mut src_rect = Rect { x: 0, y: 0, width: (dimensions.width as i32) << 16, height: (dimensions.height as i32) << 16, }; let mut alpha = VCAlpha { flags: FlagsAlpha::FIXED_ALL_PIXELS, opacity: 255, mask: 0, }; let bg_element = dispmanx::element_add( update, display, 2, &mut dest_rect, 0, &mut src_rect, dispmanx::DISPMANX_PROTECTION_NONE, &mut alpha, ptr::null_mut(), Transform::NO_ROTATE, ); let mut alpha = VCAlpha { flags: FlagsAlpha::FROM_SOURCE, opacity: 255, mask: 0, }; let mut src_rect = Rect { x: 0, y: 0, width: 0, height: 0, }; let element = dispmanx::element_add( update, display, 3, &mut dest_rect, 0, &mut src_rect, dispmanx::DISPMANX_PROTECTION_NONE, &mut alpha, ptr::null_mut(), Transform::NO_ROTATE, ); dispmanx::update_submit_sync(update); let mut window = Box::new(Window { element, width: dimensions.width as i32, height: dimensions.height as i32, }); let context_attr = [egl::EGL_CONTEXT_CLIENT_VERSION, 2, egl::EGL_NONE]; let config_attr = [ egl::EGL_RED_SIZE, 8, egl::EGL_GREEN_SIZE, 8, egl::EGL_BLUE_SIZE, 8, egl::EGL_ALPHA_SIZE, 8, egl::EGL_SURFACE_TYPE, egl::EGL_WINDOW_BIT, egl::EGL_NONE, ]; let egl_display: Result<EGLDisplay, String> = match egl::get_display(egl::EGL_DEFAULT_DISPLAY) { Some(x) => Ok(x), None => Err("Failed to get EGL display".into()), }; let egl_display: EGLDisplay = egl_display?; if !egl::initialize(egl_display, &mut 0i32, &mut 0i32) { return Err("Failed to initialize EGL".into()); } let egl_config: Result<EGLConfig, String> = match egl::choose_config(egl_display, &config_attr, 1) { Some(x) => Ok(x), None => Err("Failed to get EGL configuration".into()), }; let egl_config: EGLConfig = egl_config?; if !egl::bind_api(egl::EGL_OPENGL_ES_API) { return Err("Failed to bind EGL OpenGL ES API".into()); } let egl_context: Result<EGLContext, String> = match egl::create_context( egl_display, egl_config, egl::EGL_NO_CONTEXT, &context_attr, ) { Some(x) => Ok(x), None => Err("Failed to create EGL context".into()), }; let egl_context: EGLContext = egl_context?; let egl_surface: Result<EGLSurface, String> = match egl::create_window_surface( egl_display, egl_config, window.as_mut() as *mut _ as EGLNativeDisplayType, &[], ) { Some(x) => Ok(x), None => Err("Failed to create EGL surface".into()), }; let egl_surface: EGLSurface = egl_surface?; if !egl::make_current(egl_display, egl_surface, egl_surface, egl_context) { return Err("Failed to make EGL current context".into()); } if !egl::swap_interval(egl_display, 1) { return Err("Failed to setup swapping".into()); } Ok(Self { config: egl_config, context: egl_context, display: egl_display, surface: egl_surface, window, dispman_display: display, update, element, bg_element, }) } } impl Drop for Context { fn drop(&mut self) { println!("Context shutdown!"); egl::destroy_surface(self.display, self.surface); egl::destroy_context(self.display, self.context); egl::terminate(self.display); dispmanx::element_remove(self.update, self.element); dispmanx::element_remove(self.update, self.bg_element); dispmanx::update_submit_sync(self.update); if !dispmanx::display_close(self.dispman_display) { println!("Display shutdown successful."); } else { println!("Display shutdown failed."); } bcm_host::deinit(); } }
use egl; use egl::{EGLConfig, EGLContext, EGLDisplay, EGLNativeDisplayType, EGLSurface}; use videocore::bcm_host; use videocore::dispmanx; use videocore::dispmanx::{ DisplayHandle, ElementHandle, FlagsAlpha, Transform, UpdateHandle, VCAlpha, Window, }; use videocore::image::Rect; use videocore::bcm_host::GraphicsDisplaySize; use std::ptr; pub struct Context { pub config: EGLConfig, pub context: EGLContext, pub display: EGLDisplay, pub surface: EGLSurface, #[allow(dead_code)] window: Box<Window>, pub dispman_display: DisplayHandle, pub update: UpdateHandle, pub element: ElementHandle, pub bg_element: ElementHandle, } impl Context { pub fn get_resolution() -> GraphicsDisplaySize { bcm_host::graphics_get_display_size(0).unwrap() } pub fn swap_buffers(&self) -> bool { egl::swap_buffers(self.display, self.surface) } pub fn build() -> Result<Self, String> { bcm_host::init(); let display = dispmanx::display_open(0); let update = dispmanx::update_start(0); let dimensions: Result<GraphicsDisplaySize, String> = match bcm_host::graphics_get_display_size(0) { Some(x) => Ok(x), None => Err("bcm_host::init() did not succeed".into()), }; let dimensions = dimensions?; println!("Display size: {}x{}", dimensions.width, dimensions.height); let mut dest_rect = Rect { x: 0, y: 0, width: dimensions.width as i32, height: dimensions.height as i32, }; let mut src_rect = Rect { x: 0, y: 0, width: (dimensions.width as i32) << 16, height: (dimensions.height as i32) << 16, }; let mut alpha = VCAlpha { flags: FlagsAlpha::FIXED_ALL_PIXELS, opacity: 255, mask: 0, }; let bg_element = dispmanx::element_add( update, display, 2, &mut dest_rect, 0, &mut src_rect, dispmanx::DISPMANX_PROTECTION_NONE, &mut alpha, ptr::null_mut(), Transform::NO_ROTATE, ); let mut alpha = VCAlpha { flags: FlagsAlpha::FROM_SOURCE, opacity: 255, mask: 0, }; let mut src_rect = Rect { x: 0, y: 0, width: 0, height: 0, }; let element = dispmanx::element_add( update, display, 3, &mut dest_rect, 0, &mut src_rect, dispmanx::DISPMANX_PROTECTION_NONE, &mut alpha, ptr::null_mut(), Transform::NO_ROTATE,
("Display shutdown successful."); } else { println!("Display shutdown failed."); } bcm_host::deinit(); } }
); dispmanx::update_submit_sync(update); let mut window = Box::new(Window { element, width: dimensions.width as i32, height: dimensions.height as i32, }); let context_attr = [egl::EGL_CONTEXT_CLIENT_VERSION, 2, egl::EGL_NONE]; let config_attr = [ egl::EGL_RED_SIZE, 8, egl::EGL_GREEN_SIZE, 8, egl::EGL_BLUE_SIZE, 8, egl::EGL_ALPHA_SIZE, 8, egl::EGL_SURFACE_TYPE, egl::EGL_WINDOW_BIT, egl::EGL_NONE, ]; let egl_display: Result<EGLDisplay, String> = match egl::get_display(egl::EGL_DEFAULT_DISPLAY) { Some(x) => Ok(x), None => Err("Failed to get EGL display".into()), }; let egl_display: EGLDisplay = egl_display?; if !egl::initialize(egl_display, &mut 0i32, &mut 0i32) { return Err("Failed to initialize EGL".into()); } let egl_config: Result<EGLConfig, String> = match egl::choose_config(egl_display, &config_attr, 1) { Some(x) => Ok(x), None => Err("Failed to get EGL configuration".into()), }; let egl_config: EGLConfig = egl_config?; if !egl::bind_api(egl::EGL_OPENGL_ES_API) { return Err("Failed to bind EGL OpenGL ES API".into()); } let egl_context: Result<EGLContext, String> = match egl::create_context( egl_display, egl_config, egl::EGL_NO_CONTEXT, &context_attr, ) { Some(x) => Ok(x), None => Err("Failed to create EGL context".into()), }; let egl_context: EGLContext = egl_context?; let egl_surface: Result<EGLSurface, String> = match egl::create_window_surface( egl_display, egl_config, window.as_mut() as *mut _ as EGLNativeDisplayType, &[], ) { Some(x) => Ok(x), None => Err("Failed to create EGL surface".into()), }; let egl_surface: EGLSurface = egl_surface?; if !egl::make_current(egl_display, egl_surface, egl_surface, egl_context) { return Err("Failed to make EGL current context".into()); } if !egl::swap_interval(egl_display, 1) { return Err("Failed to setup swapping".into()); } Ok(Self { config: egl_config, context: egl_context, display: egl_display, surface: egl_surface, window, dispman_display: display, update, element, bg_element, }) } } impl Drop for Context { fn drop(&mut self) { println!("Context shutdown!"); egl::destroy_surface(self.display, self.surface); egl::destroy_context(self.display, self.context); egl::terminate(self.display); dispmanx::element_remove(self.update, self.element); dispmanx::element_remove(self.update, self.bg_element); dispmanx::update_submit_sync(self.update); if !dispmanx::display_close(self.dispman_display) { println!
random
[ { "content": "/// Loads a configuration file.\n\npub fn load_config(dir: String) -> LeaffrontConfig {\n\n let mut f = File::open(dir).expect(\"Config file not found\");\n\n\n\n let mut config_string = String::new();\n\n f.read_to_string(&mut config_string).unwrap();\n\n\n\n toml::from_str(&config_st...
Rust
src/modules/import_export.rs
lilith645/Maat-Editor3D
bbde60db0555e05bfed2be313d886fa0a3386b35
use csv; use crate::modules::WorldObject; use crate::modules::scenes::GameOptions; use crate::modules::Logs; use crate::cgmath::Vector3; use std::fs::File; use std::fs; pub fn get_models(logs: &mut Logs) -> Vec<(String, String, bool)> { if let Err(e) = fs::create_dir_all("./Models") { logs.add_error(e.to_string()); } let paths = fs::read_dir("./Models/").unwrap(); let mut models = Vec::new(); for path in paths { models.push(path.unwrap().path().display().to_string()); } let mut known_models = Vec::new(); for i in 0..models.len() { let mut location = models[i].to_string(); let mut name = "".to_string(); let b = location.pop(); let l = location.pop(); let g = location.pop(); let full_stop = location.pop(); if full_stop.unwrap() == '.' && g.unwrap() == 'g' && l.unwrap() == 'l' && b.unwrap() == 'b' { loop { let letter = location.pop(); if let Some(letter) = letter { name.push_str(&letter.to_string()); if letter == '/' { name.pop(); name = name.chars().rev().collect::<String>(); break; } } else { break; } } known_models.push((name, models[i].to_string(), false)); } } known_models } pub fn export(scene_name: String, world_objects: &Vec<WorldObject>, camera_details: &GameOptions, logs: &mut Logs) { if let Err(e) = fs::create_dir_all("./Scenes/".to_owned() + &scene_name) { logs.add_error(e.to_string()); } match csv::Writer::from_path("./Scenes/".to_owned() + &scene_name + "/" + &scene_name + ".csv") { Ok(mut file) => { file.write_record(&["id", "name", "model", "location", "instanced", "x", "y", "z", "rot_x", "rot_y", "rot_z", "size_x", "size_y", "size_z"]).unwrap(); for object in world_objects { let id = object.id().to_string(); let name = object.name().to_string(); let model = object.model(); let location = object.location(); let instanced = object.instanced_rendered().to_string(); let x = object.position().x.to_string(); let y = object.position().y.to_string(); let z = object.position().z.to_string(); let rot_x = object.rotation().x.to_string(); let rot_y = object.rotation().y.to_string(); let rot_z = object.rotation().z.to_string(); let size_x = object.size().x.to_string(); let size_y = object.size().y.to_string(); let size_z = object.size().z.to_string(); if let Err(e) = file.write_record(&[id, name, model, location, instanced, x, y, z, rot_x, rot_y, rot_z, size_x, size_y, size_z]) { logs.add_error(e.to_string()); } } file.flush().unwrap(); }, Err(e) => { logs.add_error(e.to_string()); } } match csv::Writer::from_path("./Scenes/".to_owned() + &scene_name + "/camera.csv") { Ok(mut file) => { file.write_record(&["type", "target_id", "distance", "x", "y", "z"]).unwrap(); let camera_type = camera_details.camera_type.to_string(); let target_id = camera_details.camera_target.to_string(); let distance = camera_details.camera_distance.to_string(); let x = camera_details.camera_location.x.to_string(); let y = camera_details.camera_location.y.to_string(); let z = camera_details.camera_location.z.to_string(); file.write_record(&[camera_type, target_id, distance, x, y, z]).unwrap(); file.flush().unwrap(); }, Err(e) => { logs.add_error(e.to_string()); } } } pub fn import(scene_name: String, logs: &mut Logs) -> (Vec<(String, String)>, Vec<WorldObject>, GameOptions) { let mut world_objects = Vec::new(); let mut used_models: Vec<(String, String)> = Vec::new(); let mut game_options = GameOptions::new(); match File::open("./Scenes/".to_owned() + &scene_name + "/" + &scene_name + ".csv") { Ok(file) => { let mut reader = csv::Reader::from_reader(file); for whole_object in reader.records() { match whole_object { Ok(object) => { let id: u32 = object[0].parse().unwrap(); let name: String = object[1].parse().unwrap(); let model: String = object[2].parse().unwrap(); let location: String = object[3].parse().unwrap(); let instanced: bool = object[4].parse().unwrap(); let x: f32 = object[5].parse().unwrap(); let y: f32 = object[6].parse().unwrap(); let z: f32 = object[7].parse().unwrap(); let rot_x: f32 = object[8].parse().unwrap(); let rot_y: f32 = object[9].parse().unwrap(); let rot_z: f32 = object[10].parse().unwrap(); let size_x: f32 = object[11].parse().unwrap(); let size_y: f32 = object[12].parse().unwrap(); let size_z: f32 = object[13].parse().unwrap(); let mut unique = true; for i in 0..used_models.len() { if used_models[i].0 == model { unique = false; break; } } if unique { used_models.push((model.to_string(), location.to_string())); } world_objects.push(WorldObject::new_with_data(id, name, scene_name.to_string(), model, location, Vector3::new(x, y, z), Vector3::new(rot_x, rot_y, rot_z), Vector3::new(size_x, size_y, size_z), instanced)); }, Err(e) => { logs.add_error("Scene details data:".to_owned() + &e.to_string()); } } } }, Err(e) => { logs.add_error("Scene details: ".to_owned() + &e.to_string()); }, } match File::open("./Scenes/".to_owned() + &scene_name + "/camera.csv") { Ok(file) => { let mut reader = csv::Reader::from_reader(file); for whole_object in reader.records() { match whole_object { Ok(object) => { let camera_type: i32 = object[0].parse().unwrap(); let target_id: i32 = object[1].parse().unwrap(); let distance: f32 = object[2].parse().unwrap(); let x: f32 = object[3].parse().unwrap(); let y: f32 = object[4].parse().unwrap(); let z: f32 = object[5].parse().unwrap(); game_options.camera_type = camera_type; game_options.camera_target = target_id; game_options.camera_distance = distance; game_options.camera_location = Vector3::new(x,y,z); }, Err(e) => { logs.add_error(e.to_string()); } } } }, Err(e) => { logs.add_error("Camera: ".to_owned() + &e.to_string()); } } (used_models, world_objects, game_options) }
use csv; use crate::modules::WorldObject; use crate::modules::scenes::GameOptions; use crate::modules::Logs; use crate::cgmath::Vector3; use std::fs::File; use std::fs; pub fn get_models(logs: &mut Logs) -> Vec<(String, String, bool)> { if let Err(e) = fs::create_dir_all("./Models") { logs.add_error(e.to_string()); } let paths = fs::read_dir("./Models/").unwrap(); let mut models = Vec::new(); for path in paths { models.push(path.unwrap().path().display().to_string()); } let mut known_models = Vec::new(); for i in 0..models.len() { let mut location = models[i].to_string(); let mut name = "".to_string(); let b = location.pop(); let l = location.pop(); let g = location.pop(); let full_stop = location.pop(); if full_stop.unwrap() == '.' && g.unwrap() == 'g' && l.unwrap() == 'l' && b.unwrap() == 'b' { loop { let letter = location.pop(); if let Some(letter) = letter { name.push_str(&letter.to_string()); if letter == '/' { name.pop(); name = name.char
rot_x", "rot_y", "rot_z", "size_x", "size_y", "size_z"]).unwrap(); for object in world_objects { let id = object.id().to_string(); let name = object.name().to_string(); let model = object.model(); let location = object.location(); let instanced = object.instanced_rendered().to_string(); let x = object.position().x.to_string(); let y = object.position().y.to_string(); let z = object.position().z.to_string(); let rot_x = object.rotation().x.to_string(); let rot_y = object.rotation().y.to_string(); let rot_z = object.rotation().z.to_string(); let size_x = object.size().x.to_string(); let size_y = object.size().y.to_string(); let size_z = object.size().z.to_string(); if let Err(e) = file.write_record(&[id, name, model, location, instanced, x, y, z, rot_x, rot_y, rot_z, size_x, size_y, size_z]) { logs.add_error(e.to_string()); } } file.flush().unwrap(); }, Err(e) => { logs.add_error(e.to_string()); } } match csv::Writer::from_path("./Scenes/".to_owned() + &scene_name + "/camera.csv") { Ok(mut file) => { file.write_record(&["type", "target_id", "distance", "x", "y", "z"]).unwrap(); let camera_type = camera_details.camera_type.to_string(); let target_id = camera_details.camera_target.to_string(); let distance = camera_details.camera_distance.to_string(); let x = camera_details.camera_location.x.to_string(); let y = camera_details.camera_location.y.to_string(); let z = camera_details.camera_location.z.to_string(); file.write_record(&[camera_type, target_id, distance, x, y, z]).unwrap(); file.flush().unwrap(); }, Err(e) => { logs.add_error(e.to_string()); } } } pub fn import(scene_name: String, logs: &mut Logs) -> (Vec<(String, String)>, Vec<WorldObject>, GameOptions) { let mut world_objects = Vec::new(); let mut used_models: Vec<(String, String)> = Vec::new(); let mut game_options = GameOptions::new(); match File::open("./Scenes/".to_owned() + &scene_name + "/" + &scene_name + ".csv") { Ok(file) => { let mut reader = csv::Reader::from_reader(file); for whole_object in reader.records() { match whole_object { Ok(object) => { let id: u32 = object[0].parse().unwrap(); let name: String = object[1].parse().unwrap(); let model: String = object[2].parse().unwrap(); let location: String = object[3].parse().unwrap(); let instanced: bool = object[4].parse().unwrap(); let x: f32 = object[5].parse().unwrap(); let y: f32 = object[6].parse().unwrap(); let z: f32 = object[7].parse().unwrap(); let rot_x: f32 = object[8].parse().unwrap(); let rot_y: f32 = object[9].parse().unwrap(); let rot_z: f32 = object[10].parse().unwrap(); let size_x: f32 = object[11].parse().unwrap(); let size_y: f32 = object[12].parse().unwrap(); let size_z: f32 = object[13].parse().unwrap(); let mut unique = true; for i in 0..used_models.len() { if used_models[i].0 == model { unique = false; break; } } if unique { used_models.push((model.to_string(), location.to_string())); } world_objects.push(WorldObject::new_with_data(id, name, scene_name.to_string(), model, location, Vector3::new(x, y, z), Vector3::new(rot_x, rot_y, rot_z), Vector3::new(size_x, size_y, size_z), instanced)); }, Err(e) => { logs.add_error("Scene details data:".to_owned() + &e.to_string()); } } } }, Err(e) => { logs.add_error("Scene details: ".to_owned() + &e.to_string()); }, } match File::open("./Scenes/".to_owned() + &scene_name + "/camera.csv") { Ok(file) => { let mut reader = csv::Reader::from_reader(file); for whole_object in reader.records() { match whole_object { Ok(object) => { let camera_type: i32 = object[0].parse().unwrap(); let target_id: i32 = object[1].parse().unwrap(); let distance: f32 = object[2].parse().unwrap(); let x: f32 = object[3].parse().unwrap(); let y: f32 = object[4].parse().unwrap(); let z: f32 = object[5].parse().unwrap(); game_options.camera_type = camera_type; game_options.camera_target = target_id; game_options.camera_distance = distance; game_options.camera_location = Vector3::new(x,y,z); }, Err(e) => { logs.add_error(e.to_string()); } } } }, Err(e) => { logs.add_error("Camera: ".to_owned() + &e.to_string()); } } (used_models, world_objects, game_options) }
s().rev().collect::<String>(); break; } } else { break; } } known_models.push((name, models[i].to_string(), false)); } } known_models } pub fn export(scene_name: String, world_objects: &Vec<WorldObject>, camera_details: &GameOptions, logs: &mut Logs) { if let Err(e) = fs::create_dir_all("./Scenes/".to_owned() + &scene_name) { logs.add_error(e.to_string()); } match csv::Writer::from_path("./Scenes/".to_owned() + &scene_name + "/" + &scene_name + ".csv") { Ok(mut file) => { file.write_record(&["id", "name", "model", "location", "instanced", "x", "y", "z", "
random
[ { "content": "fn benchmark(draw_calls: &mut Vec<DrawCall>, dimensions: Vector2<f32>) {\n\n draw_calls.push(DrawCall::draw_text_basic(Vector2::new(dimensions.x - 80.0, 15.0), \n\n Vector2::new(64.0, 64.0), \n\n Vector4::new(1.0,...
Rust
src/nodes/item.rs
olefasting/rust_rpg_toolkit
3f82a0fd4175f0b65518ceda1319416d5bf0ae1b
use crate::prelude::*; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ItemKind { OneHandedWeapon, TwoHandedWeapon, Misc, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ItemParams { pub id: String, pub name: String, pub description: String, #[serde( default, with = "json::opt_vec2", skip_serializing_if = "Option::is_none" )] pub position: Option<Vec2>, pub kind: ItemKind, pub weight: f32, #[serde(default, rename = "ability", skip_serializing_if = "Option::is_none")] pub ability_id: Option<String>, pub sprite: Sprite, #[serde(default)] pub is_quest_item: bool, } impl Default for ItemParams { fn default() -> Self { ItemParams { id: "".to_string(), name: "Unnamed Item".to_string(), description: "".to_string(), position: Default::default(), kind: ItemKind::Misc, weight: 0.1, ability_id: None, sprite: Default::default(), is_quest_item: false, } } } #[derive(Clone)] pub struct Item { pub id: String, pub name: String, pub description: String, pub position: Vec2, pub kind: ItemKind, pub weight: f32, pub is_quest_item: bool, ability: Option<AbilityParams>, sprite: Sprite, } impl Item { pub fn new(params: ItemParams) -> Self { let resources = storage::get::<Resources>(); let ability = if let Some(ability_id) = params.ability_id { Some(resources.abilities.get(&ability_id).cloned().unwrap()) } else { None }; Item { id: params.id, position: params.position.unwrap_or_default(), kind: params.kind, name: params.name, description: params.description, weight: params.weight, is_quest_item: params.is_quest_item, ability, sprite: params.sprite, } } pub fn add_node(params: ItemParams) -> Handle<Self> { scene::add_node(Self::new(params)) } pub fn to_params(&self) -> ItemParams { let ability_id = self.ability.as_ref().map(|ability| ability.id.clone()); ItemParams { id: self.id.clone(), name: self.name.clone(), description: self.description.clone(), position: Some(self.position), kind: self.kind.clone(), weight: self.weight, ability_id, sprite: self.sprite.clone(), is_quest_item: self.is_quest_item, } } } impl BufferedDraw for Item { fn buffered_draw(&mut self) { self.sprite.draw(self.position, 0.0); } fn get_z_index(&self) -> f32 { self.position.y } fn get_bounds(&self) -> Bounds { Bounds::Point(self.position) } } impl Node for Item { fn draw(node: RefMut<Self>) { let mut draw_buffer = scene::find_node_by_type::<DrawBuffer<Self>>().unwrap(); draw_buffer.buffered.push(node.handle()); } } #[derive(Debug, Clone)] pub struct Credits { pub position: Vec2, pub amount: u32, pub sprite: Sprite, } impl Credits { pub fn new(position: Vec2, amount: u32) -> Self { Credits { position, amount, sprite: Sprite { texture_id: "credits".to_string(), tile_size: uvec2(8, 8), ..Default::default() }, } } pub fn add_node(position: Vec2, amount: u32) -> Handle<Self> { scene::add_node(Self::new(position, amount)) } } impl BufferedDraw for Credits { fn buffered_draw(&mut self) { self.sprite.draw(self.position, 0.0); } fn get_z_index(&self) -> f32 { self.position.y } fn get_bounds(&self) -> Bounds { Bounds::Point(self.position) } } impl Node for Credits { fn ready(node: RefMut<Self>) { let mut draw_buffer = scene::find_node_by_type::<DrawBuffer<Credits>>().unwrap(); draw_buffer.buffered.push(node.handle()); } }
use crate::prelude::*; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ItemKind { OneHandedWeapon, TwoHandedWeapon, Misc, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ItemParams { pub id: String, pub name: String, pub description: String, #[serde( default, with = "json::opt_vec2", skip_serializing_if = "Option::is_none" )] pub position: Option<Vec2>, pub kind: ItemKind, pub weight: f32, #[serde(default, rename = "ability", skip_serializing_if = "Option::is_none")] pub ability_id: Option<String>, pub sprite: Sprite, #[serde(default)] pub is_quest_item: bool, } impl Default for ItemParams { fn default() -> Self { ItemParams { id: "".to_string(), name: "Unnamed Item".to_string(), description: "".to_string(), position: Default::default(), kind: ItemKind::Misc, weight: 0.1, ability_id: None, sprite: Default::default(), is_quest_item: false, } } } #[derive(Clone)] pub struct Item { pub id: String, pub name: String, pub description: String, pub position: Vec2, pub kind: ItemKind, pub weight: f32, pub is_quest_item: bool, ability: Option<AbilityParams>, sprite: Sprite, } impl Item { pub fn new(params: ItemParams) -> Self { let resources = storage::get::<Resources>(); let ability = if let Some(ability_id) = params.ability_id { Some(resources.abilities.get(&ability_id).cloned().unwrap()) } else { None }; Item { id: params.id, position: params.position.unwrap_or_default(), kind: params.kind, name: params.name, description: params.description, weight: params.weight, is_quest_item: params.is_quest_item, ability, sprite: params.sprite, } } pub fn add_node(params: ItemParams) -> Handle<Self> { scene::add_node(Self::new(params)) } pub fn to_params(&self) -> ItemParams { let ability_id = self.ability.as_ref().map(|ability| ability.id.clone()); ItemParams { id: self.id.clone(), name: self.name.clone(), description: self.description.clone(), position: Some(self.position), kind: self.kind.clone(), weight: self.weight, ability_id, sprite: self.sprite.clone(), is_quest_item: self.is_quest_item, } } } impl BufferedDraw for Item { fn buffered_draw(&mut self) { self.sprite.draw(self.position, 0.0); } fn get_z_index(&self) -> f32 { self.position.y } fn get_bounds(&self) -> Bounds { Bounds::Point(self.position) } } impl Node for Item { fn draw(node: RefMut<Self>) { let mut draw_buffer = scene::find_node_by_type::<DrawBuffer<Self>>().unwrap(); draw_buffer.buffered.push(node.handle()); } } #[derive(Debug, Clone)] pub struct Credits { pub position: Vec2, pub amount: u32, pub sprite: Sprite, } impl Credits { pub fn new(position: Vec2, amount: u32) -> Self { Credits { position, amount, sprite: Sprite {
pub fn add_node(position: Vec2, amount: u32) -> Handle<Self> { scene::add_node(Self::new(position, amount)) } } impl BufferedDraw for Credits { fn buffered_draw(&mut self) { self.sprite.draw(self.position, 0.0); } fn get_z_index(&self) -> f32 { self.position.y } fn get_bounds(&self) -> Bounds { Bounds::Point(self.position) } } impl Node for Credits { fn ready(node: RefMut<Self>) { let mut draw_buffer = scene::find_node_by_type::<DrawBuffer<Credits>>().unwrap(); draw_buffer.buffered.push(node.handle()); } }
texture_id: "credits".to_string(), tile_size: uvec2(8, 8), ..Default::default() }, } }
function_block-function_prefix_line
[ { "content": "pub fn default_behavior_set() -> String {\n\n DEFAULT_BEHAVIOR_SET_ID.to_string()\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub struct ActorBehaviorParams {\n\n pub aggression: ActorAggression,\n\n #[serde(\n\n default,\n\n with = \"json::opt_vec2\",\n\n...
Rust
capi/src/session.rs
jws121295/dansible
4c32335b048560352135480ab0216ff5be6bd8fa
use libc::{c_int, c_char}; use std::ffi::CStr; use std::slice::from_raw_parts; use std::sync::mpsc; use std::boxed::FnBox; use std::sync::Mutex; use librespot::session::{Session, Config, Bitrate}; use eventual::{Async, AsyncResult, Future}; use cstring_cache::CStringCache; use types::sp_error; use types::sp_error::*; use types::sp_session_config; use types::sp_session_callbacks; static mut global_session: Option<(*const sp_session, *const Mutex<mpsc::Sender<SpSessionEvent>>)> = None; pub type SpSessionEvent = Box<FnBox(&mut SpSession) -> ()>; pub struct SpSession { pub session: Session, cache: CStringCache, rx: mpsc::Receiver<SpSessionEvent>, pub callbacks: &'static sp_session_callbacks, } impl SpSession { pub unsafe fn global() -> &'static SpSession { &*global_session.unwrap().0 } pub fn run<F: FnOnce(&mut SpSession) -> () + 'static>(event: F) { let tx = unsafe { &*global_session.unwrap().1 }; tx.lock().unwrap().send(Box::new(event)).unwrap(); } pub fn receive<T, E, F>(future: Future<T, E>, handler: F) where T : Send, E: Send, F : FnOnce(&mut SpSession, AsyncResult<T, E>) -> () + Send + 'static { future.receive(move |result| { SpSession::run(move |session| { handler(session, result); }) }) } } #[allow(non_camel_case_types)] pub type sp_session = SpSession; #[no_mangle] pub unsafe extern "C" fn sp_session_create(c_config: *const sp_session_config, c_session: *mut *mut sp_session) -> sp_error { assert!(global_session.is_none()); let c_config = &*c_config; let application_key = from_raw_parts::<u8>(c_config.application_key as *const u8, c_config.application_key_size); let user_agent = CStr::from_ptr(c_config.user_agent).to_string_lossy().into_owned(); let device_name = CStr::from_ptr(c_config.device_id).to_string_lossy().into_owned(); let cache_location = CStr::from_ptr(c_config.cache_location).to_string_lossy().into_owned(); let config = Config { application_key: application_key.to_owned(), user_agent: user_agent, device_name: device_name, cache_location: cache_location.into(), bitrate: Bitrate::Bitrate160, }; let (tx, rx) = mpsc::channel(); let session = SpSession { session: Session::new(config), cache: CStringCache::new(), rx: rx, callbacks: &*c_config.callbacks, }; let session = Box::into_raw(Box::new(session)); let tx = Box::into_raw(Box::new(Mutex::new(tx))); global_session = Some((session, tx)); *c_session = session; SP_ERROR_OK } #[no_mangle] pub unsafe extern "C" fn sp_session_release(c_session: *mut sp_session) -> sp_error { global_session = None; drop(Box::from_raw(c_session)); SP_ERROR_OK } #[no_mangle] pub unsafe extern "C" fn sp_session_login(c_session: *mut sp_session, c_username: *const c_char, c_password: *const c_char, _remember_me: bool, _blob: *const c_char) -> sp_error { let session = &*c_session; let username = CStr::from_ptr(c_username).to_string_lossy().into_owned(); let password = CStr::from_ptr(c_password).to_string_lossy().into_owned(); { let session = session.session.clone(); SpSession::receive(Future::spawn(move || { session.login_password(username, password) }), |session, result| { result.unwrap(); { let session = session.session.clone(); ::std::thread::spawn(move || { loop { session.poll(); } }); } }); } SP_ERROR_OK } #[no_mangle] pub unsafe extern "C" fn sp_session_user_name(c_session: *mut sp_session) -> *const c_char { let session = &mut *c_session; let username = session.session.username(); session.cache.intern(&username).as_ptr() } #[no_mangle] pub unsafe extern "C" fn sp_session_user_country(c_session: *mut sp_session) -> c_int { let session = &*c_session; let country = session.session.country(); country.chars().fold(0, |acc, x| { acc << 8 | (x as u32) }) as c_int } #[no_mangle] pub unsafe extern "C" fn sp_session_process_events(c_session: *mut sp_session, next_timeout: *mut c_int) -> sp_error { let session = &mut *c_session; if !next_timeout.is_null() { *next_timeout = 10; } let event = session.rx.recv().unwrap(); event.call_box((session,)); SP_ERROR_OK }
use libc::{c_int, c_char}; use std::ffi::CStr; use std::slice::from_raw_parts; use std::sync::mpsc; use std::boxed::FnBox; use std::sync::Mutex; use librespot::session::{Session, Config, Bitrate}; use eventual::{Async, AsyncResult, Future}; use cstring_cache::CStringCache; use types::sp_error; use types::sp_error::*; use types::sp_session_config; use types::sp_session_callbacks; static mut global_session: Option<(*const sp_session, *const Mutex<mpsc::Sender<SpSessionEvent>>)> = None; pub type SpSessionEvent = Box<FnBox(&mut SpSession) -> ()>; pub struct SpSession { pub session: Session, cache: CStringCache, rx: mpsc::Receiver<SpSessionEvent>, pub callbacks: &'static sp_session_callbacks, } impl SpSession { pub unsafe fn global() -> &'static SpSession { &*global_session.unwrap().0 } pub fn run<F: FnOnce(&mut SpSession) -> () + 'static>(event: F) { let tx = unsafe { &*global
pub unsafe extern "C" fn sp_session_release(c_session: *mut sp_session) -> sp_error { global_session = None; drop(Box::from_raw(c_session)); SP_ERROR_OK } #[no_mangle] pub unsafe extern "C" fn sp_session_login(c_session: *mut sp_session, c_username: *const c_char, c_password: *const c_char, _remember_me: bool, _blob: *const c_char) -> sp_error { let session = &*c_session; let username = CStr::from_ptr(c_username).to_string_lossy().into_owned(); let password = CStr::from_ptr(c_password).to_string_lossy().into_owned(); { let session = session.session.clone(); SpSession::receive(Future::spawn(move || { session.login_password(username, password) }), |session, result| { result.unwrap(); { let session = session.session.clone(); ::std::thread::spawn(move || { loop { session.poll(); } }); } }); } SP_ERROR_OK } #[no_mangle] pub unsafe extern "C" fn sp_session_user_name(c_session: *mut sp_session) -> *const c_char { let session = &mut *c_session; let username = session.session.username(); session.cache.intern(&username).as_ptr() } #[no_mangle] pub unsafe extern "C" fn sp_session_user_country(c_session: *mut sp_session) -> c_int { let session = &*c_session; let country = session.session.country(); country.chars().fold(0, |acc, x| { acc << 8 | (x as u32) }) as c_int } #[no_mangle] pub unsafe extern "C" fn sp_session_process_events(c_session: *mut sp_session, next_timeout: *mut c_int) -> sp_error { let session = &mut *c_session; if !next_timeout.is_null() { *next_timeout = 10; } let event = session.rx.recv().unwrap(); event.call_box((session,)); SP_ERROR_OK }
_session.unwrap().1 }; tx.lock().unwrap().send(Box::new(event)).unwrap(); } pub fn receive<T, E, F>(future: Future<T, E>, handler: F) where T : Send, E: Send, F : FnOnce(&mut SpSession, AsyncResult<T, E>) -> () + Send + 'static { future.receive(move |result| { SpSession::run(move |session| { handler(session, result); }) }) } } #[allow(non_camel_case_types)] pub type sp_session = SpSession; #[no_mangle] pub unsafe extern "C" fn sp_session_create(c_config: *const sp_session_config, c_session: *mut *mut sp_session) -> sp_error { assert!(global_session.is_none()); let c_config = &*c_config; let application_key = from_raw_parts::<u8>(c_config.application_key as *const u8, c_config.application_key_size); let user_agent = CStr::from_ptr(c_config.user_agent).to_string_lossy().into_owned(); let device_name = CStr::from_ptr(c_config.device_id).to_string_lossy().into_owned(); let cache_location = CStr::from_ptr(c_config.cache_location).to_string_lossy().into_owned(); let config = Config { application_key: application_key.to_owned(), user_agent: user_agent, device_name: device_name, cache_location: cache_location.into(), bitrate: Bitrate::Bitrate160, }; let (tx, rx) = mpsc::channel(); let session = SpSession { session: Session::new(config), cache: CStringCache::new(), rx: rx, callbacks: &*c_config.callbacks, }; let session = Box::into_raw(Box::new(session)); let tx = Box::into_raw(Box::new(Mutex::new(tx))); global_session = Some((session, tx)); *c_session = session; SP_ERROR_OK } #[no_mangle]
random
[ { "content": "pub fn add_session_arguments(opts: &mut getopts::Options) {\n\n opts.optopt(\"c\", \"cache\", \"Path to a directory where files will be cached.\", \"CACHE\")\n\n .reqopt(\"n\", \"name\", \"Device name\", \"NAME\")\n\n .optopt(\"b\", \"bitrate\", \"Bitrate (96, 160 or 320). Default...
Rust
src/main.rs
svenstaro/cargo2junit
8f6555bccd025b794e041b2f6ce46321ec12cb91
extern crate junit_report; extern crate serde; use junit_report::*; use serde::{Deserialize, Serialize}; use std; use std::collections::BTreeSet; use std::io::*; #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] struct SuiteResults { passed: usize, failed: usize, } #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] #[serde(tag = "event")] enum SuiteEvent { #[serde(rename = "started")] Started { test_count: usize }, #[serde(rename = "ok")] Ok { #[serde(flatten)] results: SuiteResults, }, #[serde(rename = "failed")] Failed { #[serde(flatten)] results: SuiteResults, }, } #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] #[serde(tag = "event")] enum TestEvent { #[serde(rename = "started")] Started { name: String }, #[serde(rename = "ok")] Ok { name: String }, #[serde(rename = "failed")] Failed { name: String, stdout: String }, #[serde(rename = "ignored")] Ignored { name: String }, #[serde(rename = "timeout")] Timeout { name: String }, } #[derive(Serialize, Deserialize, Debug, PartialEq)] #[serde(untagged)] enum Event { #[serde(rename = "suite")] Suite { #[serde(flatten)] event: SuiteEvent, }, #[serde(rename = "test")] TestStringTime { #[serde(flatten)] event: TestEvent, duration: Option<f64>, exec_time: Option<String>, }, #[serde(rename = "test")] TestFloatTime { #[serde(flatten)] event: TestEvent, duration: Option<f64>, exec_time: Option<f64>, }, } impl Event { fn get_duration(&self) -> Duration { match &self { Event::Suite { event: _ } => panic!(), Event::TestStringTime { event: _, duration, exec_time, } => { let duration_ns = match (duration, exec_time) { (_, Some(s)) => { assert_eq!(s.chars().last(), Some('s')); let seconds_chars = &(s[0..(s.len() - 1)]); let seconds = seconds_chars.parse::<f64>().unwrap(); (seconds * 1_000_000_000.0) as i64 } (Some(ms), None) => (ms * 1_000_000.0) as i64, (None, None) => 0, }; Duration::nanoseconds(duration_ns) }, Event::TestFloatTime { event: _, duration, exec_time, } => { let duration_ns = match (duration, exec_time) { (_, Some(seconds)) => { (seconds * 1_000_000_000.0) as i64 } (Some(ms), None) => (ms * 1_000_000.0) as i64, (None, None) => 0, }; Duration::nanoseconds(duration_ns) } } } } fn split_name(full_name: &str) -> (&str, String) { let mut parts: Vec<&str> = full_name.split("::").collect(); let name = parts.pop().unwrap_or(""); let module_path = parts.join("::"); return (name, module_path); } fn parse<T: BufRead>( input: T, suite_name_prefix: &str, timestamp: DateTime<Utc>, ) -> Result<Report> { let mut r = Report::new(); let mut suite_index = 0; let mut current_suite: Option<TestSuite> = None; let mut tests: BTreeSet<String> = BTreeSet::new(); for line in input.lines() { let line = line?; if line.chars().filter(|c| !c.is_whitespace()).next() != Some('{') { continue; } let e: Event = match serde_json::from_str(&line) { Ok(event) => Ok(event), Err(orig_err) => { let line = line.replace("\\", "\\\\"); match serde_json::from_str(&line) { Ok(event) => Ok(event), Err(_) => Err(Error::new( ErrorKind::Other, format!("Error parsing '{}': {}", &line, orig_err), )), } } }?; match &e { Event::Suite { event } => match event { SuiteEvent::Started { test_count: _ } => { assert!(current_suite.is_none()); assert!(tests.is_empty()); let ts = TestSuite::new(&format!("{} #{}", suite_name_prefix, suite_index)) .set_timestamp(timestamp); current_suite = Some(ts); suite_index += 1; } SuiteEvent::Ok { results: _ } | SuiteEvent::Failed { results: _ } => { assert_eq!(None, tests.iter().next()); r = r.add_testsuite( current_suite.expect("Suite complete event found outside of suite!"), ); current_suite = None; } }, Event::TestStringTime { event, duration: _, exec_time: _, } | Event::TestFloatTime { event, duration: _, exec_time: _, } => { let current_suite = current_suite .as_mut() .expect("Test event found outside of suite!"); let duration = e.get_duration(); match event { TestEvent::Started { name } => { assert!(tests.insert(name.clone())); } TestEvent::Ok { name } => { assert!(tests.remove(name)); let (name, module_path) = split_name(&name); *current_suite = current_suite.clone().add_testcase( TestCase::success(&name, duration).set_classname(module_path.as_str()), ); } TestEvent::Failed { name, stdout } => { assert!(tests.remove(name)); let (name, module_path) = split_name(&name); *current_suite = current_suite.clone().add_testcase( TestCase::failure(&name, duration, "cargo test", &stdout) .set_classname(module_path.as_str()), ); } TestEvent::Ignored { name } => { assert!(tests.remove(name)); } TestEvent::Timeout { name: _ } => { } } } } } Ok(r) } fn main() -> Result<()> { let timestamp = Utc::now(); let stdin = std::io::stdin(); let stdin = stdin.lock(); let report = parse(stdin, "cargo test", timestamp)?; let stdout = std::io::stdout(); let stdout = stdout.lock(); report .write_xml(stdout) .map_err(|e| Error::new(ErrorKind::Other, format!("{}", e)))?; Ok(()) } #[cfg(test)] mod tests { use crate::parse; use junit_report::*; use regex::Regex; use std::io::*; fn parse_bytes(bytes: &[u8]) -> Result<Report> { parse(BufReader::new(bytes), "cargo test", Utc::now()) } fn parse_string(input: &str) -> Result<Report> { parse_bytes(input.as_bytes()) } fn normalize(input: &str) -> String { let date_regex = Regex::new(r"(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d+)\+00:00").unwrap(); date_regex .replace_all(input, "TIMESTAMP") .replace("\r\n", "\n") } fn assert_output(report: &Report, expected: &[u8]) { let mut output = Vec::new(); report.write_xml(&mut output).unwrap(); let output = normalize(std::str::from_utf8(&output).unwrap()); let expected = normalize(std::str::from_utf8(expected).unwrap()); assert_eq!(output, expected); } #[test] fn error_on_garbage() { assert!(parse_string("{garbage}").is_err()); } #[test] fn success_self() { let report = parse_bytes(include_bytes!("test_inputs/self.json")) .expect("Could not parse test input"); let suite = &report.testsuites()[0]; let test_cases = suite.testcases(); assert_eq!(test_cases[0].name(), "error_on_garbage"); assert_eq!(*test_cases[0].classname(), Some("tests".to_string())); assert_eq!(test_cases[0].time(), &Duration::nanoseconds(213_100)); assert_output(&report, include_bytes!("expected_outputs/self.json.out")); } #[test] fn success_self_exec_time() { let report = parse_bytes(include_bytes!("test_inputs/self_exec_time.json")) .expect("Could not parse test input"); let suite = &report.testsuites()[0]; let test_cases = suite.testcases(); assert_eq!(test_cases[4].name(), "az_func_regression"); assert_eq!(*test_cases[0].classname(), Some("tests".to_string())); assert_eq!(test_cases[4].time(), &Duration::milliseconds(72)); assert_output( &report, include_bytes!("expected_outputs/self_exec_time.json.out"), ); } #[test] fn success_single_suite() { let report = parse_bytes(include_bytes!("test_inputs/success.json")) .expect("Could not parse test input"); assert_output(&report, include_bytes!("expected_outputs/success.json.out")); } #[test] fn success_timeout() { let report = parse_bytes(include_bytes!("test_inputs/timeout.json")) .expect("Could not parse test input"); let suite = &report.testsuites()[0]; let test_cases = suite.testcases(); assert_eq!(test_cases[0].name(), "long_execution_time"); assert_eq!(*test_cases[0].classname(), Some("tests".to_string())); assert!(test_cases[0].is_success()); assert_output(&report, include_bytes!("expected_outputs/timeout.json.out")); } #[test] fn failded_single_suite() { let report = parse_bytes(include_bytes!("test_inputs/failed.json")) .expect("Could not parse test input"); assert_output(&report, include_bytes!("expected_outputs/failed.json.out")); } #[test] fn multi_suite_success() { let report = parse_bytes(include_bytes!("test_inputs/multi_suite_success.json")) .expect("Could not parse test input"); assert_output( &report, include_bytes!("expected_outputs/multi_suite_success.json.out"), ); } #[test] fn cargo_project_failure() { let report = parse_bytes(include_bytes!("test_inputs/cargo_failure.json")) .expect("Could not parse test input"); assert_output( &report, include_bytes!("expected_outputs/cargo_failure.json.out"), ); } #[test] fn az_func_regression() { let report = parse_bytes(include_bytes!("test_inputs/azfunc.json")) .expect("Could not parse test input"); assert_output(&report, include_bytes!("expected_outputs/azfunc.json.out")); } #[test] fn float_time() { parse_bytes(include_bytes!("test_inputs/float_time.json")) .expect("Could not parse test input"); } }
extern crate junit_report; extern crate serde; use junit_report::*; use serde::{Deserialize, Serialize}; use std; use std::collections::BTreeSet; use std::io::*; #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] struct SuiteResults { passed: usize, failed: usize, } #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] #[serde(tag = "event")] enum SuiteEvent { #[serde(rename = "started")] Started { test_count: usize }, #[serde(rename = "ok")] Ok { #[serde(flatten)] results: SuiteResults, }, #[serde(rename = "failed")] Failed { #[serde(flatten)] results: SuiteResults, }, } #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] #[serde(tag = "event")] enum TestEvent { #[serde(rename = "started")] Started { name: String }, #[serde(rename = "ok")] Ok { name: String }, #[serde(rename = "failed")] Failed { name: String, stdout: String }, #[serde(rename = "ignored")] Ignored { name: String }, #[serde(rename = "timeout")] Timeout { name: String }, } #[derive(Serialize, Deserialize, Debug, PartialEq)] #[serde(untagged)] enum Event { #[serde(rename = "suite")] Suite { #[serde(flatten)] event: SuiteEvent, }, #[serde(rename = "test")] TestStringTime { #[serde(flatten)] event: TestEvent, duration: Option<f64>, exec_time: Option<String>, }, #[serde(rename = "test")] TestFloatTime { #[serde(flatten)] event: TestEvent, duration: Option<f64>, exec_time: Option<f64>, }, } impl Event { fn get_duration(&self) -> Duration { match &self { Event::Suite { event: _ } => panic!(), Event::TestStringTime { event: _, duration, exec_time, } => { let duration_ns = match (duration, exec_time) { (_, Some(s)) => { assert_eq!(s.chars().last(), Some('s')); let seconds_chars = &(s[0..(s.len() - 1)]); let seconds = seconds_chars.parse::<f64>().unwrap(); (seconds * 1_000_000_000.0) as i64 } (Some(ms), None) => (ms * 1_000_000.0) as i64, (None, None) => 0, }; Duration::nanoseconds(duration_ns) }, Event::TestFloatTime { event: _, duration, exec_time, } => { let duration_ns = match (duration, exec_time) { (_, Some(seconds)) => { (seconds * 1_000_000_000.0) as i64 } (Some(ms), None) => (ms * 1_000_000.0) as i64, (None, None) => 0, }; Duration::nanoseconds(duration_ns) } } } } fn split_name(full_name: &str) -> (&str, String) { let mut parts: Vec<&str> = full_name.split("::").collect(); let name = parts.pop().unwrap_or(""); let module_path = parts.join("::"); return (name, module_path); } fn parse<T: BufRead>( input: T, suite_name_prefix: &str, timestamp: DateTime<Utc>, ) -> Result<Report> { let mut r = Report::new(); let mut suite_index = 0; let mut current_suite: Option<TestSuite> = None; let mut tests: BTreeSet<String> = BTreeSet::new(); for line in input.lines() { let line = line?; if line.chars().filter(|c| !c.is_whitespace()).next() != Some('{') { continue; } let e: Event = match serde_json::from_str(&line) { Ok(event) => Ok(event), Err(orig_err) => { let line = line.replace("\\", "\\\\"); match serde_json::from_str(&line) { Ok(event) => Ok(event), Err(_) => Err(Error::new( ErrorKind::Other, format!("Error parsing '{}': {}", &line, orig_err), )), } } }?; match &e { Event::Suite { event } => match event { SuiteEvent::Started { test_count: _ } => { assert!(current_suite.is_none()); assert!(tests.is_empty()); let ts = TestSuite::new(&format!("{} #{}", suite_name_prefix, suite_index)) .set_timestamp(timestamp); current_suite = Some(ts); suite_index += 1; } SuiteEvent::Ok { results: _ } | SuiteEvent::Failed { results: _ } => { assert_eq!(None, tests.iter().next()); r = r.add_testsuite( current_suite.expect("Suite complete event found outside of suite!"), ); current_suite = None; } }, Event::TestStringTime { event, duration: _, exec_time: _, } | Event::TestFloatTime { event, duration: _, exec_time: _, } => { let current_suite = current_suite .as_mut() .expect("Test event found outside of suite!"); let duration = e.get_duration(); match event { TestEvent::Started { name } => { assert!(tests.insert(name.clone())); } TestEvent::Ok { name } => { assert!(tests.remove(name)); let (name, module_path) = split_name(&name); *current_suite = current_suite.clone().add_testcase( TestCase::success(&name, duration).set_classname(module_path.as_str()), ); } TestEvent::Failed { name, stdout } => { assert!(tests.remove(name)); let (name, module_path) = split_name(&name); *current_suite = current_suite.clone().add_testcase( TestCase::failure(&name, duration, "cargo test", &stdout) .set_classname(module_path.as_str()), ); } TestEvent::Ignored { name } => { assert!(tests.remove(name)); } TestEvent::Timeout { name: _ } => { } } } } } Ok(r) } fn main() -> Result<()> { let timestamp = Utc::now(); let stdin = std::io::stdin(); let stdin = stdin.lock(); let report = parse(stdin, "cargo test", timestamp)?; let stdout = std::io::stdout(); let stdout = stdout.lock(); report .write_xml(stdout) .map_err(|e| Error::new(ErrorKind::Other, format!("{}", e)))?; Ok(()) } #[cfg(test)] mod tests { use crate::parse; use junit_report::*; use regex::Regex; use std::io::*; fn parse_bytes(bytes: &[u8]) -> Result<Report> { parse(BufReader::new(bytes), "cargo test", Utc::now()) } fn parse_string(input: &str) -> Result<Report> { parse_bytes(input.as_bytes()) } fn normalize(input: &str) -> String { let date_regex = Regex::new(r"(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d+)\+00:00").unwrap(); date_regex .replace_all(input, "TIMESTAMP") .replace("\r\n", "\n") } fn assert_output(report: &Report, expected: &[u8]) { let mut output = Vec::new(); report.write_xml(&mut output).unwrap(); let output = normalize(std::str::from_utf8(&output).unwrap()); let expected = normalize(std::str::from_utf8(expected).unwrap()); assert_eq!(output, expected); } #[test] fn error_on_garbage() { assert!(parse_string("{garbage}").is_err()); } #[test] fn success_self() { let report = parse_bytes(include_bytes!("test_inputs/self.json")) .expect("Could not parse test input"); let suite = &report.testsuites()[0]; let test_cases = suite.testcases(); assert_eq!(test_cases[0].name(), "error_on_garbage"); assert_eq!(*test_cases[0].classname(), Some("tests".to_string())); assert_eq!(test_cases[0].time(), &Duration::nanoseconds(213_100)); assert_output(&report, include_bytes!("expected_outputs/self.json.out")); } #[test] fn success_self_exec_time() { let report = parse_bytes(include_bytes!("test_inputs/self_exec_time.json")) .expect("Could not parse test input"); let suite = &report.testsuites()[0]; let test_cases = suite.testcases(); assert_eq!(test_cases[4].name(), "az_func_regression"); assert_eq!(*test_cases[0].classname(), Some("tests".to_string())); assert_eq!(test_cases[4].time(), &Duration::milliseconds(72)); assert_output( &report, include_bytes!("expected_outputs/self_exec_time.json.out"), ); } #[test] fn success_single_suite() { let report = parse_bytes(include_bytes!("test_inputs/success.json")) .expect("Could not parse test input"); assert_output(&report, include_bytes!("expected_outputs/success.json.out")); } #[test] fn success_timeout() { let report = parse_bytes(include_bytes!("test_inputs/timeout.json")) .expect("Could not parse test input"); let suite = &report.testsuites()[0]; let test_cases = suite.testcases(); assert_eq!(test_cases[0].name(), "long_execution_time"); assert_eq!(*test_cases[0].classname(), Some("tests".to_string())); assert!(test_cases[0].is_success()); assert_output(&report, include_bytes!("expected_outputs/timeout.json.out")); } #[test] fn failded_single_suite() { let report = parse_bytes(include_bytes!("test_inputs/failed.json")) .expect("Could not parse test input"); assert_output(&report, include_bytes!("expected_outputs/failed.json.out")); } #[test] fn multi_suite_success() { let report = parse_bytes(include_bytes!("test_inputs/multi_suite_success.json")) .expect("Could not parse test input"); assert_output( &report, include_bytes!("expected_outputs/multi_suite_success.json.out"), ); } #[test]
#[test] fn az_func_regression() { let report = parse_bytes(include_bytes!("test_inputs/azfunc.json")) .expect("Could not parse test input"); assert_output(&report, include_bytes!("expected_outputs/azfunc.json.out")); } #[test] fn float_time() { parse_bytes(include_bytes!("test_inputs/float_time.json")) .expect("Could not parse test input"); } }
fn cargo_project_failure() { let report = parse_bytes(include_bytes!("test_inputs/cargo_failure.json")) .expect("Could not parse test input"); assert_output( &report, include_bytes!("expected_outputs/cargo_failure.json.out"), ); }
function_block-full_function
[ { "content": "[![Build Status](https://dev.azure.com/cargo2junit/cargo2junit/_apis/build/status/johnterickson.cargo2junit?branchName=master)](https://dev.azure.com/cargo2junit/cargo2junit/_build/latest?definitionId=1&branchName=master)\n\n\n\n# cargo2junit\n\nConverts cargo's json output (from stdin) to JUnit X...
Rust
src/stock.rs
teohhanhui/stocker
ac666f50762620b4e4e0bed39aad150f42aa056c
use crate::{ app::{Indicator, TimeFrame}, reactive::StreamExt, }; use async_compat::Compat; use chrono::{DateTime, Duration, TimeZone, Utc}; use futures::executor; use gcollections::ops::{Bounded, Difference, Union}; use im::{hashmap, ordset, HashMap, OrdSet}; use interval::interval_set::{IntervalSet, ToIntervalSet}; use reactive_rs::Stream; use std::{cell::RefCell, ops::Range, rc::Rc}; use yahoo_finance::{history, Bar, Profile, Quote, Timestamped}; #[derive(Clone, Debug, Default)] pub struct Stock { pub bars: OrdSet<Bar>, pub profile: Option<Profile>, pub quote: Option<Quote>, pub symbol: String, } impl Stock { pub fn name(&self) -> Option<&str> { match &self.profile { Some(Profile::Company(company)) => Some(company.name.as_str()), Some(Profile::Fund(fund)) => Some(fund.name.as_str()), None => None, } } } pub fn to_stock_profiles<'a, S>(stock_symbols: S) -> ToStockProfiles<S> where S: Stream<'a, Item = String>, { ToStockProfiles { stock_profile_map: Rc::new(RefCell::new(hashmap! {})), stock_symbols, } } pub struct ToStockProfiles<S> { stock_profile_map: Rc<RefCell<HashMap<String, Profile>>>, stock_symbols: S, } impl<'a, S> Stream<'a> for ToStockProfiles<S> where S: Stream<'a, Item = String>, { type Context = S::Context; type Item = Profile; fn subscribe_ctx<O>(self, mut observer: O) where O: 'a + FnMut(&Self::Context, &Self::Item), { let stock_profile_map = self.stock_profile_map.clone(); self.stock_symbols .distinct_until_changed() .subscribe_ctx(move |ctx, stock_symbol| { let profile = { let stock_profile_map = stock_profile_map.borrow(); stock_profile_map.get(stock_symbol).cloned() }; let profile = profile.unwrap_or_else(|| { let profile = executor::block_on(Compat::new(async { Profile::load(stock_symbol.as_str()).await })) .expect("profile load failed"); let mut stock_profile_map = stock_profile_map.borrow_mut(); stock_profile_map.insert(stock_symbol.clone(), profile.clone()); profile }); observer(ctx, &profile); }); } } pub fn to_stock_bar_sets<'a, S, U, R, V>( stock_symbols: S, time_frames: U, date_ranges: R, indicators: V, ) -> ToStockBarSets<S, U, R, V> where S: Stream<'a, Item = String>, U: Stream<'a, Item = TimeFrame>, R: Stream<'a, Item = Option<Range<DateTime<Utc>>>>, V: Stream<'a, Item = Option<Indicator>>, { ToStockBarSets { date_ranges, indicators, stock_bars_map: Rc::new(RefCell::new(hashmap! {})), stock_symbols, time_frames, } } type DateRangeIntervalSet = IntervalSet<i64>; type BarCoverageHashMap = HashMap<String, (OrdSet<Bar>, DateRangeIntervalSet)>; pub struct ToStockBarSets<S, U, R, V> { date_ranges: R, indicators: V, stock_bars_map: Rc<RefCell<BarCoverageHashMap>>, stock_symbols: S, time_frames: U, } impl<'a, S, U, R, V, C> Stream<'a> for ToStockBarSets<S, U, R, V> where S: Stream<'a, Item = String, Context = C>, U: Stream<'a, Item = TimeFrame>, R: Stream<'a, Item = Option<Range<DateTime<Utc>>>>, V: Stream<'a, Item = Option<Indicator>>, C: 'a + Clone + Sized, { type Context = C; type Item = OrdSet<Bar>; fn subscribe_ctx<O>(self, mut observer: O) where O: 'a + FnMut(&Self::Context, &Self::Item), { let stock_bars_map = self.stock_bars_map.clone(); self.stock_symbols .distinct_until_changed() .combine_latest( self.time_frames.distinct_until_changed(), |(stock_symbol, time_frame)| (stock_symbol.clone(), *time_frame), ) .combine_latest( self.date_ranges.distinct_until_changed(), |((stock_symbol, time_frame), date_range)| { (stock_symbol.clone(), *time_frame, date_range.clone()) }, ) .combine_latest( self.indicators.distinct_until_changed(), |((stock_symbol, time_frame, date_range), indicator)| { ( stock_symbol.clone(), *time_frame, date_range.clone(), *indicator, ) }, ) .subscribe_ctx( move |ctx, (stock_symbol, time_frame, date_range, indicator)| { let (stock_bar_set, covered_date_ranges) = { let stock_bars_map = stock_bars_map.borrow(); stock_bars_map .get(stock_symbol) .cloned() .unwrap_or((ordset![], vec![].to_interval_set())) }; let (stock_bar_set, covered_date_ranges) = if let Some(date_range) = date_range { let uncovered_date_ranges = ( date_range.start.timestamp(), (date_range.end - Duration::seconds(1)).timestamp(), ) .to_interval_set(); let uncovered_date_ranges = match indicator { Some(Indicator::BollingerBands(n, _)) => uncovered_date_ranges.union( &( (date_range.start - Duration::days(**n as i64 - 1)).timestamp(), (date_range.start - Duration::seconds(1)).timestamp(), ) .to_interval_set(), ), Some(Indicator::ExponentialMovingAverage(n)) => uncovered_date_ranges .union( &( (date_range.start - Duration::days(**n as i64 - 1)) .timestamp(), (date_range.start - Duration::seconds(1)).timestamp(), ) .to_interval_set(), ), Some(Indicator::SimpleMovingAverage(n)) => uncovered_date_ranges.union( &( (date_range.start - Duration::days(**n as i64 - 1)).timestamp(), (date_range.start - Duration::seconds(1)).timestamp(), ) .to_interval_set(), ), None => uncovered_date_ranges, }; let uncovered_date_ranges = uncovered_date_ranges.difference(&covered_date_ranges); let mut covered_date_ranges = covered_date_ranges; let mut stock_bar_set = stock_bar_set; for uncovered_date_range in uncovered_date_ranges { let bars = executor::block_on(Compat::new(async { history::retrieve_range( stock_symbol.as_str(), Utc.timestamp(uncovered_date_range.lower(), 0), Some(Utc.timestamp(uncovered_date_range.upper(), 0)), ) .await })) .expect("historical prices retrieval failed"); covered_date_ranges = covered_date_ranges.union( &(uncovered_date_range.lower(), uncovered_date_range.upper()) .to_interval_set(), ); stock_bar_set = stock_bar_set + OrdSet::from(bars); } (stock_bar_set, covered_date_ranges) } else { let bars = executor::block_on(Compat::new(async { history::retrieve_interval(stock_symbol.as_str(), time_frame.interval()) .await })) .expect("historical prices retrieval failed"); let covered_date_ranges = if let (Some(first_bar), Some(last_bar)) = (bars.first(), bars.last()) { covered_date_ranges.union( &vec![( first_bar.timestamp_seconds() as i64, last_bar.timestamp_seconds() as i64, )] .to_interval_set(), ) } else { covered_date_ranges }; let stock_bar_set = stock_bar_set + OrdSet::from(bars); (stock_bar_set, covered_date_ranges) }; observer(ctx, &stock_bar_set); let mut stock_bars_map = stock_bars_map.borrow_mut(); stock_bars_map .insert(stock_symbol.clone(), (stock_bar_set, covered_date_ranges)); }, ); } }
use crate::{ app::{Indicator, TimeFrame}, reactive::StreamExt, }; use async_compat::Compat; use chrono::{DateTime, Duration, TimeZone, Utc}; use futures::executor; use gcollections::ops::{Bounded, Difference, Union}; use im::{hashmap, ordset, HashMap, OrdSet}; use interval::interval_set::{IntervalSet, ToIntervalSet}; use reactive_rs::Stream; use std::{cell::RefCell, ops::Range, rc::Rc}; use yahoo_finance::{history, Bar, Profile, Quote, Timestamped}; #[derive(Clone, Debug, Default)] pub struct Stock { pub bars: OrdSet<Bar>, pub profile: Option<Profile>, pub quote: Option<Quote>, pub symbol: String, } impl Stock { pub fn name(&self) -> Option<&str> { match &self.profile { Some(Profile::Company(company)) => Some(company.name.as_str()), Some(Profile::Fund(fund)) => Some(fund.name.as_str()), None => None, } } } pub fn to_stock_profiles<'a, S>(stock_symbols: S) -> ToStockProfiles<S> where S: Stream<'a, Item = String>, { ToStockProfiles { stock_profile_map: Rc::new(RefCell::new(hashmap! {})), stock_symbols, } } pub struct ToStockProfiles<S> { stock_profile_map: Rc<RefCell<HashMap<String, Profile>>>, stock_symbols: S, } impl<'a, S> Stream<'a> for ToStockProfiles<S> where S: Stream<'a, Item = String>, { type Context = S::Context; type Item = Profile; fn subscribe_ctx<O>(self, mut observer: O) where O: 'a + FnMut(&Self::Context, &Self::Item), { let stock_profile_map = self.stock_profile_map.clone(); self.stock_symbols .distinct_until_changed() .subscribe_ctx(move |ctx, stock_symbol| { let profile = { let stock_profile_map = stock_profile_map.borrow(); stock_profile_map.get(stock_symbol).cloned() }; let profile = profile.unwrap_or_else(|| { let profile = executor::block_on(Compat::new(async { Profile::load(stock_symbol.as_str()).await })) .expect("profile load failed"); let mut stock_profile_map = stock_profile_map.borrow_mut(); stock_profile_map.insert(stock_symbol.clone(), profile.clone()); profile }); observer(ctx, &profile); }); } } pub fn to_stock_bar_sets<'a, S, U, R, V>( stock_symbols: S, time_frames: U, date_ranges: R, indicators: V, ) -> ToStockBarSets<S, U, R, V> where S: Stream<'a, Item = String>, U: Stream<'a, Item = TimeFrame>, R: Stream<'a, Item = Option<Range<DateTime<Utc>>>>, V: Stream<'a, Item = Option<Indicator>>, { ToStockBarSets { date_ranges, indicators, stock_bars_map: Rc::new(RefCell::new(hashmap! {})), stock_symbols, time_frames, } } type DateRangeIntervalSet = IntervalSet<i64>; type BarCoverageHashMap = HashMap<String, (OrdSet<Bar>, DateRangeIntervalSet)>; pub struct ToStockBarSets<S, U, R, V> { date_ranges: R, indicators: V, stock_bars_map: Rc<RefCell<BarCoverageHashMap>>, stock_symbols: S, time_frames: U, } impl<'a, S, U, R, V, C> Stream<'a> for ToStockBarSets<S, U, R, V> where S: Stream<'a, Item = String, Context = C>, U: Stream<'a, Item = TimeFrame>, R: Stream<'a, Item = Option<Range<DateTime<Utc>>>>, V: Stream<'a, Item = Option<Indicator>>, C: 'a + Clone + Sized, { type Context = C; type Item = OrdSet<Bar>; fn subscribe_ctx<O>(self, mut observer: O) where O: 'a + FnMut(&Self::Context, &Self::Item), { let stock_bars_map = self.stock_bars_map.clone(); self.stock_symbols .distinct_until_changed() .combine_latest( self.time_frames.distinct_until_changed(), |(stock_symbol, time_frame)| (stock_symbol.clone(), *time_frame), ) .combine_latest( self.date_ranges.distinct_until_changed(), |((stock_symbol, time_frame), date_range)| { (stock_symbol.clone(), *time_frame, date_range.clone()) }, ) .combine_latest( self.indicators.distinct_until_changed(), |((stock_symbol, time_frame, date_range), indicator)| { ( stock_symbol.clone(), *time_frame, date_range.clone(), *indicator, ) }, ) .subscribe_ctx( move |ctx, (stock_symbol, time_frame, date_range, indicator)| { let (stock_bar_set, covered_date_ranges) = { let stock_bars_map = stock_bars_map.borrow(); stock_bars_map .get(stock_symbol) .cloned() .unwrap_or((ordset![], vec![].to_interval_set())) }; let (stock_bar_set, covered_date_ranges) = if let Some(date_range) = date_range { let uncovered_date_ranges = ( date_range.start.timestamp(), (date_range.end - Duration::seconds(1)).timestamp(), ) .to_interval_set(); let uncovered_date_ranges = match indicator { Some(Indicator::BollingerBands(n, _)) => uncovered_date_ranges.union( &( (date_range.start - Duration::days(**n as i64 - 1)).timestamp(), (date_range.start - Duration::seconds(1)).timestamp(), ) .to_interval_set(), ), Some(Indicator::ExponentialMovingAverage(n)) => uncovered_date_ranges .union( &( (date_range.start - Duration::days(**n as i64 - 1)) .timestamp(), (date_range.start - Duration::seconds(1)).timestamp(), ) .to_interval_set(), ), Some(Indicator::SimpleMovingAverage(n)) => uncovered_date_ranges.union( &( (date_range.start - Duration::days(**n as i64 - 1)).timestamp(), (date_range.start - Duration::seconds(1)).timestamp(), ) .to_interval_set(), ), None => uncovered_date_ranges, }; let uncovered_date_ranges = uncovered_date_ranges.difference(&covered_date_ranges); let mut covered_date_ranges = covered_date_ranges; let mut stock_bar_set = stock_bar_set; for uncovered_date_range in uncovered_date_ranges { let bars = executor::block_on(Compat::new(async { history::retrieve_range( stock_symbol.as_str(), Utc.timestamp(uncovered_date_range.lower(), 0), Some(Utc.timestamp(uncovered_date_range.upper(), 0)), ) .await })) .expect("historical prices retrieval failed"); covered_date_ranges = covered_date_ranges.union( &(uncovered_date_range.lower(), uncovered_date_range.upper()) .to_interval_set(), ); stock_bar_set = stock_bar_set + OrdSet::from(bars); } (stock_bar_set, covered_date_ranges) } else { let bars = executor::block_on(Compat::new(async {
covered_date_ranges.union( &vec![( first_bar.timestamp_seconds() as i64, last_bar.timestamp_seconds() as i64, )] .to_interval_set(), ) } else { covered_date_ranges }; let stock_bar_set = stock_bar_set + OrdSet::from(bars); (stock_bar_set, covered_date_ranges) }; observer(ctx, &stock_bar_set); let mut stock_bars_map = stock_bars_map.borrow_mut(); stock_bars_map .insert(stock_symbol.clone(), (stock_bar_set, covered_date_ranges)); }, ); } }
history::retrieve_interval(stock_symbol.as_str(), time_frame.interval()) .await })) .expect("historical prices retrieval failed"); let covered_date_ranges = if let (Some(first_bar), Some(last_bar)) = (bars.first(), bars.last()) {
random
[ { "content": "pub fn to_date_ranges<'a, S, U, R, C>(\n\n chart_events: S,\n\n stock_symbols: U,\n\n init_stock_symbol: String,\n\n time_frames: R,\n\n init_time_frame: TimeFrame,\n\n) -> impl Stream<'a, Item = Option<DateRange>, Context = C>\n\nwhere\n\n S: Stream<'a, Item = ChartEvent, Contex...
Rust
qlib/kernel/fs/fsutil/inode/simple_file_inode.rs
abel-von/Quark
7bbba67ee1105e3b7df751a278cbad9b2af666a1
use alloc::string::String; use crate::qlib::mutex::*; use core::ops::Deref; use alloc::vec::Vec; use core::any::Any; use super::super::super::super::socket::unix::transport::unix::*; use super::super::super::mount::*; use super::super::super::attr::*; use super::super::super::inode::*; use super::super::super::flags::*; use super::super::super::file::*; use super::super::super::dirent::*; use super::super::super::super::super::linux_def::*; use super::super::super::super::task::*; use super::super::super::super::super::common::*; use super::super::super::super::super::auth::*; use super::super::super::super::kernel::time::*; use super::super::super::host::hostinodeop::*; pub trait SimpleFileTrait : Send + Sync { fn GetFile(&self, _task: &Task, _dir: &Inode, _dirent: &Dirent, _flags: FileFlags) -> Result<File> { return Err(Error::SysError(SysErr::ENXIO)) }} pub struct SimpleFileNode {} impl SimpleFileTrait for SimpleFileNode {} pub struct SimpleFileInodeInternal <T: 'static + SimpleFileTrait> { pub fsType: u64, pub unstable: UnstableAttr, pub wouldBlock: bool, pub data: T, } pub struct SimpleFileInode<T: 'static + SimpleFileTrait> (QRwLock<SimpleFileInodeInternal<T>>); impl <T: 'static + SimpleFileTrait> Deref for SimpleFileInode <T> { type Target = QRwLock<SimpleFileInodeInternal<T>>; fn deref(&self) -> &QRwLock<SimpleFileInodeInternal<T>> { &self.0 } } impl <T: 'static + SimpleFileTrait> SimpleFileInode <T> { pub fn New(task: &Task, owner: &FileOwner, perms: &FilePermissions, typ: u64, wouldBlock: bool, data: T) -> Self { let unstable = WithCurrentTime(task, &UnstableAttr { Owner: *owner, Perms: *perms, ..Default::default() }); return Self::NewWithUnstable(&unstable, typ, wouldBlock, data) } pub fn NewWithUnstable(u: &UnstableAttr, typ: u64, wouldBlock: bool, data: T) -> Self { let internal = SimpleFileInodeInternal { fsType: typ, unstable: *u, wouldBlock: wouldBlock, data: data, }; return Self(QRwLock::new(internal)) } } impl <T: 'static + SimpleFileTrait> InodeOperations for SimpleFileInode <T> { fn as_any(&self) -> &Any { self } fn IopsType(&self) -> IopsType { return IopsType::SimpleFileInode; } fn InodeType(&self) -> InodeType { return InodeType::SpecialFile; } fn InodeFileType(&self) -> InodeFileType { return InodeFileType::SimpleFileInode; } fn WouldBlock(&self) -> bool { return self.read().wouldBlock; } fn Check(&self, task: &Task, inode: &Inode, reqPerms: &PermMask) -> Result<bool> { return ContextCanAccessFile(task, inode, reqPerms) } fn Getxattr(&self, _dir: &Inode, _name: &str) -> Result<String> { return Err(Error::SysError(SysErr::EOPNOTSUPP)) } fn Setxattr(&self, _dir: &mut Inode, _name: &str, _value: &str) -> Result<()> { return Err(Error::SysError(SysErr::EOPNOTSUPP)) } fn Listxattr(&self, _dir: &Inode) -> Result<Vec<String>> { return Err(Error::SysError(SysErr::EOPNOTSUPP)) } fn Allocate(&self, _task: &Task, _dir: &mut Inode, _offset: i64, _length: i64) -> Result<()> { return Err(Error::SysError(SysErr::EOPNOTSUPP)) } fn Lookup(&self, _task: &Task, _dir: &Inode, _name: &str) -> Result<Dirent> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn Create(&self, _task: &Task, _dir: &mut Inode, _name: &str, _flags: &FileFlags, _perm: &FilePermissions) -> Result<File> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn CreateDirectory(&self, _task: &Task, _dir: &mut Inode, _name: &str, _perm: &FilePermissions) -> Result<()> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn CreateLink(&self, _task: &Task, _dir: &mut Inode, _oldname: &str, _newname: &str) -> Result<()> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn CreateHardLink(&self, _task: &Task, _dir: &mut Inode, _target: &Inode, _name: &str) -> Result<()> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn CreateFifo(&self, _task: &Task, _dir: &mut Inode, _name: &str, _perm: &FilePermissions) -> Result<()> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn Remove(&self, _task: &Task, _dir: &mut Inode, _name: &str) -> Result<()> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn RemoveDirectory(&self, _task: &Task, _dir: &mut Inode, _name: &str) -> Result<()> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn Rename(&self, _task: &Task, _dir: &mut Inode, _oldParent: &Inode, _oldname: &str, _newParent: &Inode, _newname: &str, _replacement: bool) -> Result<()> { return Err(Error::SysError(SysErr::EINVAL)) } fn Bind(&self, _task: &Task, _dir: &Inode, _name: &str, _data: &BoundEndpoint, _perms: &FilePermissions) -> Result<Dirent> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn BoundEndpoint(&self, _task: &Task, _inode: &Inode, _path: &str) -> Option<BoundEndpoint> { return None } fn GetFile(&self, task: &Task, dir: &Inode, dirent: &Dirent, flags: FileFlags) -> Result<File> { return self.read().data.GetFile(task, dir, dirent, flags) } fn ReadLink(&self, _task: &Task,_dir: &Inode) -> Result<String> { return Err(Error::SysError(SysErr::ENOLINK)) } fn GetLink(&self, _task: &Task, _dir: &Inode) -> Result<Dirent> { return Err(Error::SysError(SysErr::ENOLINK)) } fn Truncate(&self, _task: &Task, _dir: &mut Inode, _size: i64) -> Result<()> { return Err(Error::SysError(SysErr::EINVAL)) } fn IsVirtual(&self) -> bool { return false } fn UnstableAttr(&self, _task: &Task, _dir: &Inode) -> Result<UnstableAttr> { let u = self.read().unstable; return Ok(u) } fn SetPermissions(&self, task: &Task, _dir: &mut Inode, p: FilePermissions) -> bool { self.write().unstable.SetPermissions(task, &p); return true; } fn SetOwner(&self, task: &Task, _dir: &mut Inode, owner: &FileOwner) -> Result<()> { self.write().unstable.SetOwner(task, owner); return Ok(()) } fn SetTimestamps(&self, task: &Task, _dir: &mut Inode, ts: &InterTimeSpec) -> Result<()> { self.write().unstable.SetTimestamps(task, ts); return Ok(()) } fn AddLink(&self, _task: &Task) { self.write().unstable.Links += 1; } fn DropLink(&self, _task: &Task) { self.write().unstable.Links -= 1; } fn Sync(&self) -> Result<()> { return Err(Error::SysError(SysErr::ENOSYS)); } fn StatFS(&self, _task: &Task) -> Result<FsInfo> { if self.read().fsType == 0 { return Err(Error::SysError(SysErr::ENOSYS)) } return Ok(FsInfo { Type: self.read().fsType, ..Default::default() }) } fn Mappable(&self) -> Result<HostInodeOp> { return Err(Error::SysError(SysErr::ENODEV)) } } #[derive(Clone, Default, Debug)] pub struct InodeSimpleAttributesInternal { pub fsType: u64, pub unstable: UnstableAttr, } impl InodeSimpleAttributesInternal { pub fn New(task: &Task, owner: &FileOwner, perms: &FilePermissions, typ: u64) -> Self { let unstable = WithCurrentTime(task, &UnstableAttr { Owner: *owner, Perms: *perms, ..Default::default() }); let internal = InodeSimpleAttributesInternal { fsType: typ, unstable: unstable, }; return internal } } pub struct InodeSimpleAttributes(pub QRwLock<InodeSimpleAttributesInternal>); impl Default for InodeSimpleAttributes { fn default() -> Self { return Self(QRwLock::new(Default::default())) } } impl Deref for InodeSimpleAttributes { type Target = QRwLock<InodeSimpleAttributesInternal>; fn deref(&self) -> &QRwLock<InodeSimpleAttributesInternal> { &self.0 } } impl InodeSimpleAttributes { pub fn New(task: &Task, owner: &FileOwner, perms: &FilePermissions, typ: u64) -> Self { let unstable = WithCurrentTime(task, &UnstableAttr { Owner: *owner, Perms: *perms, ..Default::default() }); return Self::NewWithUnstable(&unstable, typ) } fn NewWithUnstable(u: &UnstableAttr, typ: u64) -> Self { let internal = InodeSimpleAttributesInternal { fsType: typ, unstable: *u, }; return Self(QRwLock::new(internal)) } fn UnstableAttr(&self, _task: &Task, _dir: &Inode) -> Result<UnstableAttr> { let u = self.read().unstable; return Ok(u) } fn SetPermissions(&self, task: &Task, _dir: &mut Inode, p: FilePermissions) -> bool { self.write().unstable.SetPermissions(task, &p); return true; } fn SetOwner(&self, task: &Task, _dir: &mut Inode, owner: &FileOwner) -> Result<()> { self.write().unstable.SetOwner(task, owner); return Ok(()) } fn SetTimestamps(&self, task: &Task, _dir: &mut Inode, ts: &InterTimeSpec) -> Result<()> { self.write().unstable.SetTimestamps(task, ts); return Ok(()) } fn AddLink(&self, _task: &Task) { self.write().unstable.Links += 1; } fn DropLink(&self, _task: &Task) { self.write().unstable.Links -= 1; } }
use alloc::string::String; use crate::qlib::mutex::*; use core::ops::Deref; use alloc::vec::Vec; use core::any::Any; use super::super::super::super::socket::unix::transport::unix::*; use super::super::super::mount::*; use super::super::super::attr::*; use super::super::super::inode::*; use super::super::super::flags::*; use super::super::super::file::*; use super::super::super::dirent::*; use super::super::super::super::super::linux_def::*; use super::super::super::super::task::*; use super::super::super::super::super::common::*; use super::super::super::super::super::auth::*; use super::super::super::super::kernel::time::*; use super::super::super::host::hostinodeop::*; pub trait SimpleFileTrait : Send + Sync { fn GetFile(&self, _task: &Task, _dir: &Inode, _dirent: &Dirent, _flags: FileFlags) -> Result<File> { return Err(Error::SysError(SysErr::ENXIO)) }} pub struct SimpleFileNode {} impl SimpleFileTrait for SimpleFileNode {} pub struct SimpleFileInodeInternal <T: 'static + SimpleFileTrait> { pub fsType: u64, pub unstable: UnstableAttr, pub wouldBlock: bool, pub data: T, } pub struct SimpleFileInode<T: 'static + SimpleFileTrait> (QRwLock<SimpleFileInodeInternal<T>>); impl <T: 'static + SimpleFileTrait> Deref for SimpleFileInode <T> { type Target = QRwLock<SimpleFileInodeInternal<T>>; fn deref(&self) -> &QRwLock<SimpleFileInodeInternal<T>> { &self.0 } } impl <T: 'static + SimpleFileTrait> SimpleFileInode <T> { pub fn New(task: &Task, owner: &FileOwner, perms: &FilePermissions, typ: u64, wouldBlock: bool, data: T) -> Self { let unstable = WithCurrentTime(task, &UnstableAttr { Owner: *owner, Perms: *perms, ..Default::default() }); return Self::NewWithUnstable(&unstable, typ, wouldBlock, data) } pub fn NewWithUnstable(u: &UnstableAttr, typ: u64, wouldBlock: bool, data: T) -> Self { let internal = SimpleFileInodeInternal { fsType: typ, unstable: *u, wouldBlock: wouldBlock, data: data, }; return Self(QRwLock::new(internal)) } } impl <T: 'static + SimpleFileTrait> InodeOperations for SimpleFileInode <T> { fn as_any(&self) -> &Any { self } fn IopsType(&self) -> IopsType { return IopsType::SimpleFileInode; } fn InodeType(&self) -> InodeType { return InodeType::SpecialFile; } fn InodeFileType(&self) -> InodeFileType { return InodeFileType::SimpleFileInode; } fn WouldBlock(&self) -> bool { return self.read().wouldBlock; } fn Check(&self, task: &Task, inode: &Inode, reqPerms: &PermMask) -> Result<bool> { return ContextCanAccessFile(task, inode, reqPerms) } fn Getxattr(&self, _dir: &Inode, _name: &str) -> Result<String> { return Err(Error::SysError(SysErr::EOPNOTSUPP)) } fn Setxattr(&self, _dir: &mut Inode, _name: &str, _value: &str) -> Result<()> { return Err(Error::SysError(SysErr::EOPNOTSUPP)) } fn Listxattr(&self, _dir: &Inode) -> Result<Vec<String>> { return Err(Error::SysError(SysErr::EOPNOTSUPP)) } fn Allocate(&self, _task: &Task, _dir: &mut Inode, _offset: i64, _length: i64) -> Result<()> { return Err(Error::SysError(SysErr::EOPNOTSUPP)) } fn Lookup(&self, _task: &Task, _dir: &Inode, _name: &str) -> Result<Dirent> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn Create(&self, _task: &Task, _dir: &mut Inode, _name: &str, _flags: &FileFlags, _perm: &FilePermissions) -> Result<File> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn CreateDirectory(&self, _task: &Task, _dir: &mut Inode, _name: &str, _perm: &FilePermissions) -> Result<()> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn CreateLink(&self, _task: &Task, _dir: &mut Inode, _oldname: &str, _newname: &str) -> Result<()> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn CreateHardLink(&self, _task: &Task, _dir: &mut Inode, _target: &Inode, _name: &str) -> Result<()> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn CreateFifo(&self, _task: &Task, _dir: &mut Inode, _name: &str, _perm: &FilePermissions) -> Result<()> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn Remove(&self, _task: &Task, _dir: &mut Inode, _name: &str) -> Result<()> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn RemoveDirectory(&self, _task: &Task, _dir: &mut Inode, _name: &str) -> Result<()> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn Rename(&self, _task: &Task, _dir: &mut Inode, _oldParent: &Inode, _oldname: &str, _newParent: &Inode, _newname: &str, _replacement: bool) -> Result<()> { return Err(Error::SysError(SysErr::EINVAL)) } fn Bind(&self, _task: &Task, _dir: &Inode, _name: &str, _data: &BoundEndpoint, _perms: &FilePermissions) -> Result<Dirent> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn BoundEndpoint(&self, _task: &Task, _inode: &Inode, _path: &str) -> Option<BoundEndpoint> { return None } fn GetFile(&self, task: &Task, dir: &Inode, dirent: &Dirent, flags: FileFlags) -> Result<File> { return self.read().data.GetFile(task, dir, dirent, flags) }
r::ENOSYS)) } return Ok(FsInfo { Type: self.read().fsType, ..Default::default() }) } fn Mappable(&self) -> Result<HostInodeOp> { return Err(Error::SysError(SysErr::ENODEV)) } } #[derive(Clone, Default, Debug)] pub struct InodeSimpleAttributesInternal { pub fsType: u64, pub unstable: UnstableAttr, } impl InodeSimpleAttributesInternal { pub fn New(task: &Task, owner: &FileOwner, perms: &FilePermissions, typ: u64) -> Self { let unstable = WithCurrentTime(task, &UnstableAttr { Owner: *owner, Perms: *perms, ..Default::default() }); let internal = InodeSimpleAttributesInternal { fsType: typ, unstable: unstable, }; return internal } } pub struct InodeSimpleAttributes(pub QRwLock<InodeSimpleAttributesInternal>); impl Default for InodeSimpleAttributes { fn default() -> Self { return Self(QRwLock::new(Default::default())) } } impl Deref for InodeSimpleAttributes { type Target = QRwLock<InodeSimpleAttributesInternal>; fn deref(&self) -> &QRwLock<InodeSimpleAttributesInternal> { &self.0 } } impl InodeSimpleAttributes { pub fn New(task: &Task, owner: &FileOwner, perms: &FilePermissions, typ: u64) -> Self { let unstable = WithCurrentTime(task, &UnstableAttr { Owner: *owner, Perms: *perms, ..Default::default() }); return Self::NewWithUnstable(&unstable, typ) } fn NewWithUnstable(u: &UnstableAttr, typ: u64) -> Self { let internal = InodeSimpleAttributesInternal { fsType: typ, unstable: *u, }; return Self(QRwLock::new(internal)) } fn UnstableAttr(&self, _task: &Task, _dir: &Inode) -> Result<UnstableAttr> { let u = self.read().unstable; return Ok(u) } fn SetPermissions(&self, task: &Task, _dir: &mut Inode, p: FilePermissions) -> bool { self.write().unstable.SetPermissions(task, &p); return true; } fn SetOwner(&self, task: &Task, _dir: &mut Inode, owner: &FileOwner) -> Result<()> { self.write().unstable.SetOwner(task, owner); return Ok(()) } fn SetTimestamps(&self, task: &Task, _dir: &mut Inode, ts: &InterTimeSpec) -> Result<()> { self.write().unstable.SetTimestamps(task, ts); return Ok(()) } fn AddLink(&self, _task: &Task) { self.write().unstable.Links += 1; } fn DropLink(&self, _task: &Task) { self.write().unstable.Links -= 1; } }
fn ReadLink(&self, _task: &Task,_dir: &Inode) -> Result<String> { return Err(Error::SysError(SysErr::ENOLINK)) } fn GetLink(&self, _task: &Task, _dir: &Inode) -> Result<Dirent> { return Err(Error::SysError(SysErr::ENOLINK)) } fn Truncate(&self, _task: &Task, _dir: &mut Inode, _size: i64) -> Result<()> { return Err(Error::SysError(SysErr::EINVAL)) } fn IsVirtual(&self) -> bool { return false } fn UnstableAttr(&self, _task: &Task, _dir: &Inode) -> Result<UnstableAttr> { let u = self.read().unstable; return Ok(u) } fn SetPermissions(&self, task: &Task, _dir: &mut Inode, p: FilePermissions) -> bool { self.write().unstable.SetPermissions(task, &p); return true; } fn SetOwner(&self, task: &Task, _dir: &mut Inode, owner: &FileOwner) -> Result<()> { self.write().unstable.SetOwner(task, owner); return Ok(()) } fn SetTimestamps(&self, task: &Task, _dir: &mut Inode, ts: &InterTimeSpec) -> Result<()> { self.write().unstable.SetTimestamps(task, ts); return Ok(()) } fn AddLink(&self, _task: &Task) { self.write().unstable.Links += 1; } fn DropLink(&self, _task: &Task) { self.write().unstable.Links -= 1; } fn Sync(&self) -> Result<()> { return Err(Error::SysError(SysErr::ENOSYS)); } fn StatFS(&self, _task: &Task) -> Result<FsInfo> { if self.read().fsType == 0 { return Err(Error::SysError(SysEr
random
[ { "content": "fn InodeIsDirAllocate_Allocate(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _offset: i64, _length: i64) -> Result<()> {\n\n return Err(Error::SysError(SysErr::EISDIR))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 0, "score": 637044.610642917 ...
Rust
lib/src/command/process.rs
abitrolly/watchexec
5bdd87dbf6a67360c78555924e777bd5507d5ec6
use std::process::ExitStatus; use command_group::AsyncGroupChild; use tokio::process::Child; use tracing::{debug, trace}; use crate::error::RuntimeError; #[derive(Debug)] pub enum Process { None, Grouped(AsyncGroupChild), Ungrouped(Child), Done(ExitStatus), } impl Default for Process { fn default() -> Self { Process::None } } impl Process { #[cfg(unix)] pub fn signal(&mut self, sig: command_group::Signal) -> Result<(), RuntimeError> { use command_group::UnixChildExt; match self { Self::None | Self::Done(_) => Ok(()), Self::Grouped(c) => { debug!(signal=%sig, pgid=?c.id(), "sending signal to process group"); c.signal(sig) } Self::Ungrouped(c) => { debug!(signal=%sig, pid=?c.id(), "sending signal to process"); c.signal(sig) } } .map_err(RuntimeError::Process) } pub async fn kill(&mut self) -> Result<(), RuntimeError> { match self { Self::None | Self::Done(_) => Ok(()), Self::Grouped(c) => { debug!(pgid=?c.id(), "killing process group"); c.kill() } Self::Ungrouped(c) => { debug!(pid=?c.id(), "killing process"); c.kill().await } } .map_err(RuntimeError::Process) } pub fn is_running(&mut self) -> Result<bool, RuntimeError> { match self { Self::None | Self::Done(_) => Ok(false), Self::Grouped(c) => c.try_wait().map(|status| { trace!("try-waiting on process group"); if let Some(status) = status { trace!(?status, "converting to ::Done"); *self = Self::Done(status); true } else { false } }), Self::Ungrouped(c) => c.try_wait().map(|status| { trace!("try-waiting on process"); if let Some(status) = status { trace!(?status, "converting to ::Done"); *self = Self::Done(status); true } else { false } }), } .map_err(RuntimeError::Process) } pub async fn wait(&mut self) -> Result<Option<ExitStatus>, RuntimeError> { match self { Self::None => Ok(None), Self::Done(status) => Ok(Some(*status)), Self::Grouped(c) => { trace!("waiting on process group"); let status = c.wait().await.map_err(|err| RuntimeError::IoError { about: "waiting on process group", err, })?; trace!(?status, "converting to ::Done"); *self = Self::Done(status); Ok(Some(status)) } Self::Ungrouped(c) => { trace!("waiting on process"); let status = c.wait().await.map_err(|err| RuntimeError::IoError { about: "waiting on process (ungrouped)", err, })?; trace!(?status, "converting to ::Done"); *self = Self::Done(status); Ok(Some(status)) } } .map_err(RuntimeError::Process) } }
use std::process::ExitStatus; use command_group::AsyncGroupChild; use tokio::process::Child; use tracing::{debug, trace}; use crate::error::RuntimeError; #[derive(Debug)] pub enum Process { None, Grouped(AsyncGroupChild), Ungrouped(Child), Done(ExitStatus), } impl Default for Process { fn default() -> Self { Process::None } } impl Process { #[cfg(unix)] pub fn signal(&mut self, sig: command_group::Signal) -> Result<(), RuntimeError> { use command_group::UnixChildExt;
.map_err(RuntimeError::Process) } pub async fn kill(&mut self) -> Result<(), RuntimeError> { match self { Self::None | Self::Done(_) => Ok(()), Self::Grouped(c) => { debug!(pgid=?c.id(), "killing process group"); c.kill() } Self::Ungrouped(c) => { debug!(pid=?c.id(), "killing process"); c.kill().await } } .map_err(RuntimeError::Process) } pub fn is_running(&mut self) -> Result<bool, RuntimeError> { match self { Self::None | Self::Done(_) => Ok(false), Self::Grouped(c) => c.try_wait().map(|status| { trace!("try-waiting on process group"); if let Some(status) = status { trace!(?status, "converting to ::Done"); *self = Self::Done(status); true } else { false } }), Self::Ungrouped(c) => c.try_wait().map(|status| { trace!("try-waiting on process"); if let Some(status) = status { trace!(?status, "converting to ::Done"); *self = Self::Done(status); true } else { false } }), } .map_err(RuntimeError::Process) } pub async fn wait(&mut self) -> Result<Option<ExitStatus>, RuntimeError> { match self { Self::None => Ok(None), Self::Done(status) => Ok(Some(*status)), Self::Grouped(c) => { trace!("waiting on process group"); let status = c.wait().await.map_err(|err| RuntimeError::IoError { about: "waiting on process group", err, })?; trace!(?status, "converting to ::Done"); *self = Self::Done(status); Ok(Some(status)) } Self::Ungrouped(c) => { trace!("waiting on process"); let status = c.wait().await.map_err(|err| RuntimeError::IoError { about: "waiting on process (ungrouped)", err, })?; trace!(?status, "converting to ::Done"); *self = Self::Done(status); Ok(Some(status)) } } .map_err(RuntimeError::Process) } }
match self { Self::None | Self::Done(_) => Ok(()), Self::Grouped(c) => { debug!(signal=%sig, pgid=?c.id(), "sending signal to process group"); c.signal(sig) } Self::Ungrouped(c) => { debug!(signal=%sig, pid=?c.id(), "sending signal to process"); c.signal(sig) } }
if_condition
[ { "content": "/// Convenience function to check a glob pattern from a string.\n\n///\n\n/// This parses the glob and wraps any error with nice [miette] diagnostics.\n\npub fn check_glob(glob: &str) -> Result<(), GlobParseError> {\n\n\tlet mut builder = GitignoreBuilder::new(\"/\");\n\n\tif let Err(err) = builde...
Rust
web_glitz/src/rendering/attachment.rs
RSSchermer/web_glitz.rs
a2e26ef0156705f0b5ac7707c4fc24a4a994d84b
use std::marker; use std::sync::Arc; use web_sys::WebGl2RenderingContext as Gl; use crate::image::format::{ InternalFormat, Multisamplable, Multisample, RenderbufferFormat, TextureFormat, }; use crate::image::renderbuffer::{Renderbuffer, RenderbufferData}; use crate::image::texture_2d::{ Level as Texture2DLevel, LevelMut as Texture2DLevelMut, Texture2DData, }; use crate::image::texture_2d_array::{ LevelLayer as Texture2DArrayLevelLayer, LevelLayerMut as Texture2DArrayLevelLayerMut, Texture2DArrayData, }; use crate::image::texture_3d::{ LevelLayer as Texture3DLevelLayer, LevelLayerMut as Texture3DLevelLayerMut, Texture3DData, }; use crate::image::texture_cube::{ CubeFace, LevelFace as TextureCubeLevelFace, LevelFaceMut as TextureCubeLevelFaceMut, TextureCubeData, }; use crate::util::JsId; pub trait AsAttachment { type Format: InternalFormat; fn as_attachment(&mut self) -> Attachment<Self::Format>; } impl<'a, T> AsAttachment for &'a mut T where T: AsAttachment, { type Format = T::Format; fn as_attachment(&mut self) -> Attachment<Self::Format> { (*self).as_attachment() } } impl<'a, F> AsAttachment for Texture2DLevelMut<'a, F> where F: TextureFormat, { type Format = F; fn as_attachment(&mut self) -> Attachment<Self::Format> { Attachment::from_texture_2d_level(&self) } } impl<'a, F> AsAttachment for Texture2DArrayLevelLayerMut<'a, F> where F: TextureFormat, { type Format = F; fn as_attachment(&mut self) -> Attachment<Self::Format> { Attachment::from_texture_2d_array_level_layer(&self) } } impl<'a, F> AsAttachment for Texture3DLevelLayerMut<'a, F> where F: TextureFormat, { type Format = F; fn as_attachment(&mut self) -> Attachment<Self::Format> { Attachment::from_texture_3d_level_layer(&self) } } impl<'a, F> AsAttachment for TextureCubeLevelFaceMut<'a, F> where F: TextureFormat, { type Format = F; fn as_attachment(&mut self) -> Attachment<Self::Format> { Attachment::from_texture_cube_level_face(&self) } } impl<F> AsAttachment for Renderbuffer<F> where F: RenderbufferFormat + 'static, { type Format = F; fn as_attachment(&mut self) -> Attachment<Self::Format> { Attachment::from_renderbuffer(self) } } pub struct Attachment<'a, F> { data: AttachmentData, marker: marker::PhantomData<&'a F>, } impl<'a, F> Attachment<'a, F> { pub(crate) fn from_texture_2d_level(image: &Texture2DLevel<'a, F>) -> Self where F: TextureFormat, { Attachment { data: AttachmentData { context_id: image.texture_data().context_id(), kind: AttachableImageRefKind::Texture2DLevel { data: image.texture_data().clone(), level: image.level() as u8, }, width: image.width(), height: image.height(), }, marker: marker::PhantomData, } } pub(crate) fn from_texture_2d_array_level_layer(image: &Texture2DArrayLevelLayer<'a, F>) -> Self where F: TextureFormat, { Attachment { data: AttachmentData { context_id: image.texture_data().context_id(), kind: AttachableImageRefKind::Texture2DArrayLevelLayer { data: image.texture_data().clone(), level: image.level() as u8, layer: image.layer() as u16, }, width: image.width(), height: image.height(), }, marker: marker::PhantomData, } } pub(crate) fn from_texture_3d_level_layer(image: &Texture3DLevelLayer<'a, F>) -> Self where F: TextureFormat, { Attachment { data: AttachmentData { context_id: image.texture_data().context_id(), kind: AttachableImageRefKind::Texture3DLevelLayer { data: image.texture_data().clone(), level: image.level() as u8, layer: image.layer() as u16, }, width: image.width(), height: image.height(), }, marker: marker::PhantomData, } } pub(crate) fn from_texture_cube_level_face(image: &TextureCubeLevelFace<'a, F>) -> Self where F: TextureFormat, { Attachment { data: AttachmentData { context_id: image.texture_data().context_id(), kind: AttachableImageRefKind::TextureCubeLevelFace { data: image.texture_data().clone(), level: image.level() as u8, face: image.face(), }, width: image.width(), height: image.height(), }, marker: marker::PhantomData, } } pub(crate) fn from_renderbuffer(render_buffer: &'a Renderbuffer<F>) -> Self { Attachment { data: AttachmentData { context_id: render_buffer.data().context_id(), kind: AttachableImageRefKind::Renderbuffer { data: render_buffer.data().clone(), }, width: render_buffer.width(), height: render_buffer.height(), }, marker: marker::PhantomData, } } pub(crate) fn into_data(self) -> AttachmentData { self.data } } pub trait AsMultisampleAttachment { type SampleFormat: InternalFormat + Multisamplable; fn as_multisample_attachment(&mut self) -> MultisampleAttachment<Self::SampleFormat>; } impl<'a, T> AsMultisampleAttachment for &'a mut T where T: AsMultisampleAttachment, { type SampleFormat = T::SampleFormat; fn as_multisample_attachment(&mut self) -> MultisampleAttachment<Self::SampleFormat> { (*self).as_multisample_attachment() } } impl<F> AsMultisampleAttachment for Renderbuffer<Multisample<F>> where F: RenderbufferFormat + Multisamplable + 'static, { type SampleFormat = F; fn as_multisample_attachment(&mut self) -> MultisampleAttachment<Self::SampleFormat> { MultisampleAttachment::from_renderbuffer(self) } } pub struct MultisampleAttachment<'a, F> where F: Multisamplable, { internal: MultisampleAttachmentInternal<'a, F>, } impl<'a, F> MultisampleAttachment<'a, F> where F: Multisamplable, { pub(crate) fn from_renderbuffer(renderbuffer: &'a Renderbuffer<Multisample<F>>) -> Self { MultisampleAttachment { internal: renderbuffer.into(), } } pub fn samples(&self) -> u8 { self.internal.samples() } pub(crate) fn into_data(self) -> AttachmentData { self.internal.into_data() } } enum MultisampleAttachmentInternal<'a, F> where F: Multisamplable, { Renderbuffer(&'a Renderbuffer<Multisample<F>>), } impl<'a, F> MultisampleAttachmentInternal<'a, F> where F: Multisamplable, { fn samples(&self) -> u8 { match self { MultisampleAttachmentInternal::Renderbuffer(renderbufer) => renderbufer.samples(), } } fn into_data(self) -> AttachmentData { match self { MultisampleAttachmentInternal::Renderbuffer(renderbuffer) => AttachmentData { context_id: renderbuffer.data().context_id(), kind: AttachableImageRefKind::Renderbuffer { data: renderbuffer.data().clone(), }, width: renderbuffer.width(), height: renderbuffer.height(), }, } } } impl<'a, F> From<&'a Renderbuffer<Multisample<F>>> for MultisampleAttachmentInternal<'a, F> where F: Multisamplable, { fn from(renderbuffer: &'a Renderbuffer<Multisample<F>>) -> Self { MultisampleAttachmentInternal::Renderbuffer(renderbuffer) } } #[derive(Clone, Hash, PartialEq)] pub(crate) struct AttachmentData { pub(crate) context_id: u64, pub(crate) kind: AttachableImageRefKind, pub(crate) width: u32, pub(crate) height: u32, } impl AttachmentData { pub(crate) fn id(&self) -> JsId { match &self.kind { AttachableImageRefKind::Texture2DLevel { data, .. } => data.id().unwrap(), AttachableImageRefKind::Texture2DArrayLevelLayer { data, .. } => data.id().unwrap(), AttachableImageRefKind::Texture3DLevelLayer { data, .. } => data.id().unwrap(), AttachableImageRefKind::TextureCubeLevelFace { data, .. } => data.id().unwrap(), AttachableImageRefKind::Renderbuffer { data, .. } => data.id().unwrap(), } } pub(crate) fn attach(&self, gl: &Gl, target: u32, slot: u32) { unsafe { match &self.kind { AttachableImageRefKind::Texture2DLevel { data, level } => { data.id().unwrap().with_value_unchecked(|texture_object| { gl.framebuffer_texture_2d( target, slot, Gl::TEXTURE_2D, Some(&texture_object), *level as i32, ); }); } AttachableImageRefKind::Texture2DArrayLevelLayer { data, level, layer } => { data.id().unwrap().with_value_unchecked(|texture_object| { gl.framebuffer_texture_layer( target, slot, Some(&texture_object), *level as i32, *layer as i32, ); }); } AttachableImageRefKind::Texture3DLevelLayer { data, level, layer } => { data.id().unwrap().with_value_unchecked(|texture_object| { gl.framebuffer_texture_layer( target, slot, Some(&texture_object), *level as i32, *layer as i32, ); }); } AttachableImageRefKind::TextureCubeLevelFace { data, level, face } => { data.id().unwrap().with_value_unchecked(|texture_object| { gl.framebuffer_texture_2d( target, slot, face.id(), Some(&texture_object), *level as i32, ); }); } AttachableImageRefKind::Renderbuffer { data } => { data.id() .unwrap() .with_value_unchecked(|renderbuffer_object| { gl.framebuffer_renderbuffer( target, slot, Gl::RENDERBUFFER, Some(&renderbuffer_object), ); }); } } } } } #[derive(Clone, Hash, PartialEq)] pub(crate) enum AttachableImageRefKind { Texture2DLevel { data: Arc<Texture2DData>, level: u8, }, Texture2DArrayLevelLayer { data: Arc<Texture2DArrayData>, level: u8, layer: u16, }, Texture3DLevelLayer { data: Arc<Texture3DData>, level: u8, layer: u16, }, TextureCubeLevelFace { data: Arc<TextureCubeData>, level: u8, face: CubeFace, }, Renderbuffer { data: Arc<RenderbufferData>, }, }
use std::marker; use std::sync::Arc; use web_sys::WebGl2RenderingContext as Gl; use crate::image::format::{ InternalFormat, Multisamplable, Multisample, RenderbufferFormat, TextureFormat, }; use crate::image::renderbuffer::{Renderbuffer, RenderbufferData}; use crate::image::texture_2d::{ Level as Texture2DLevel, LevelMut as Texture2DLevelMut, Texture2DData, }; use crate::image::texture_2d_array::{ LevelLayer as Texture2DArrayLevelLayer, LevelLayerMut as Texture2DArrayLevelLayerMut, Texture2DArrayData, }; use crate::image::texture_3d::{ LevelLayer as Texture3DLevelLayer, LevelLayerMut as Texture3DLevelLayerMut, Texture3DData, }; use crate::image::texture_cube::{ CubeFace, LevelFace as TextureCubeLevelFace, LevelFaceMut as TextureCubeLevelFaceMut, TextureCubeData, }; use crate::util::JsId; pub trait AsAttachment { type Format: InternalFormat; fn as_attachment(&mut self) -> Attachment<Self::Format>; } impl<'a, T> AsAttachment for &'a mut T where T: AsAttachment, { type Format = T::Format; fn as_attachment(&mut self) -> Attachment<Self::Format> { (*self).as_attachment() } } impl<'a, F> AsAttachment for Texture2DLevelMut<'a, F> where F: TextureFormat, { type Format = F; fn as_attachment(&mut self) -> Attachment<Self::Format> { Attachment::from_texture_2d_level(&self) } } impl<'a, F> AsAttachment for Texture2DArrayLevelLayerMut<'a, F> where F: TextureFormat, { type Format = F; fn as_attachment(&mut self) -> Attachment<Self::Format> { Attachment::from_texture_2d_array_level_layer(&self) } } impl<'a, F> AsAttachment for Texture3DLevelLayerMut<'a, F> where F: TextureFormat, { type Format = F; fn as_attachment(&mut self) -> Attachment<Self::Format> { Attachment::from_texture_3d_level_layer(&self) } } impl<'a, F> AsAttachment for TextureCubeLevelFaceMut<'a, F> where F: TextureFormat, { type Format = F; fn as_attachment(&mut self) -> Attachment<Self::Format> { Attachment::from_texture_cube_level_face(&self) } } impl<F> AsAttachment for Renderbuffer<F> where F: RenderbufferFormat + 'static, { type Format = F; fn as_attachment(&mut self) -> Attachment<Self::Format> { Attachment::from_renderbuffer(self) } } pub struct Attachment<'a, F> { data: AttachmentData, marker: marker::PhantomData<&'a F>, } impl<'a, F> Attachment<'a, F> {
pub(crate) fn from_texture_2d_array_level_layer(image: &Texture2DArrayLevelLayer<'a, F>) -> Self where F: TextureFormat, { Attachment { data: AttachmentData { context_id: image.texture_data().context_id(), kind: AttachableImageRefKind::Texture2DArrayLevelLayer { data: image.texture_data().clone(), level: image.level() as u8, layer: image.layer() as u16, }, width: image.width(), height: image.height(), }, marker: marker::PhantomData, } } pub(crate) fn from_texture_3d_level_layer(image: &Texture3DLevelLayer<'a, F>) -> Self where F: TextureFormat, { Attachment { data: AttachmentData { context_id: image.texture_data().context_id(), kind: AttachableImageRefKind::Texture3DLevelLayer { data: image.texture_data().clone(), level: image.level() as u8, layer: image.layer() as u16, }, width: image.width(), height: image.height(), }, marker: marker::PhantomData, } } pub(crate) fn from_texture_cube_level_face(image: &TextureCubeLevelFace<'a, F>) -> Self where F: TextureFormat, { Attachment { data: AttachmentData { context_id: image.texture_data().context_id(), kind: AttachableImageRefKind::TextureCubeLevelFace { data: image.texture_data().clone(), level: image.level() as u8, face: image.face(), }, width: image.width(), height: image.height(), }, marker: marker::PhantomData, } } pub(crate) fn from_renderbuffer(render_buffer: &'a Renderbuffer<F>) -> Self { Attachment { data: AttachmentData { context_id: render_buffer.data().context_id(), kind: AttachableImageRefKind::Renderbuffer { data: render_buffer.data().clone(), }, width: render_buffer.width(), height: render_buffer.height(), }, marker: marker::PhantomData, } } pub(crate) fn into_data(self) -> AttachmentData { self.data } } pub trait AsMultisampleAttachment { type SampleFormat: InternalFormat + Multisamplable; fn as_multisample_attachment(&mut self) -> MultisampleAttachment<Self::SampleFormat>; } impl<'a, T> AsMultisampleAttachment for &'a mut T where T: AsMultisampleAttachment, { type SampleFormat = T::SampleFormat; fn as_multisample_attachment(&mut self) -> MultisampleAttachment<Self::SampleFormat> { (*self).as_multisample_attachment() } } impl<F> AsMultisampleAttachment for Renderbuffer<Multisample<F>> where F: RenderbufferFormat + Multisamplable + 'static, { type SampleFormat = F; fn as_multisample_attachment(&mut self) -> MultisampleAttachment<Self::SampleFormat> { MultisampleAttachment::from_renderbuffer(self) } } pub struct MultisampleAttachment<'a, F> where F: Multisamplable, { internal: MultisampleAttachmentInternal<'a, F>, } impl<'a, F> MultisampleAttachment<'a, F> where F: Multisamplable, { pub(crate) fn from_renderbuffer(renderbuffer: &'a Renderbuffer<Multisample<F>>) -> Self { MultisampleAttachment { internal: renderbuffer.into(), } } pub fn samples(&self) -> u8 { self.internal.samples() } pub(crate) fn into_data(self) -> AttachmentData { self.internal.into_data() } } enum MultisampleAttachmentInternal<'a, F> where F: Multisamplable, { Renderbuffer(&'a Renderbuffer<Multisample<F>>), } impl<'a, F> MultisampleAttachmentInternal<'a, F> where F: Multisamplable, { fn samples(&self) -> u8 { match self { MultisampleAttachmentInternal::Renderbuffer(renderbufer) => renderbufer.samples(), } } fn into_data(self) -> AttachmentData { match self { MultisampleAttachmentInternal::Renderbuffer(renderbuffer) => AttachmentData { context_id: renderbuffer.data().context_id(), kind: AttachableImageRefKind::Renderbuffer { data: renderbuffer.data().clone(), }, width: renderbuffer.width(), height: renderbuffer.height(), }, } } } impl<'a, F> From<&'a Renderbuffer<Multisample<F>>> for MultisampleAttachmentInternal<'a, F> where F: Multisamplable, { fn from(renderbuffer: &'a Renderbuffer<Multisample<F>>) -> Self { MultisampleAttachmentInternal::Renderbuffer(renderbuffer) } } #[derive(Clone, Hash, PartialEq)] pub(crate) struct AttachmentData { pub(crate) context_id: u64, pub(crate) kind: AttachableImageRefKind, pub(crate) width: u32, pub(crate) height: u32, } impl AttachmentData { pub(crate) fn id(&self) -> JsId { match &self.kind { AttachableImageRefKind::Texture2DLevel { data, .. } => data.id().unwrap(), AttachableImageRefKind::Texture2DArrayLevelLayer { data, .. } => data.id().unwrap(), AttachableImageRefKind::Texture3DLevelLayer { data, .. } => data.id().unwrap(), AttachableImageRefKind::TextureCubeLevelFace { data, .. } => data.id().unwrap(), AttachableImageRefKind::Renderbuffer { data, .. } => data.id().unwrap(), } } pub(crate) fn attach(&self, gl: &Gl, target: u32, slot: u32) { unsafe { match &self.kind { AttachableImageRefKind::Texture2DLevel { data, level } => { data.id().unwrap().with_value_unchecked(|texture_object| { gl.framebuffer_texture_2d( target, slot, Gl::TEXTURE_2D, Some(&texture_object), *level as i32, ); }); } AttachableImageRefKind::Texture2DArrayLevelLayer { data, level, layer } => { data.id().unwrap().with_value_unchecked(|texture_object| { gl.framebuffer_texture_layer( target, slot, Some(&texture_object), *level as i32, *layer as i32, ); }); } AttachableImageRefKind::Texture3DLevelLayer { data, level, layer } => { data.id().unwrap().with_value_unchecked(|texture_object| { gl.framebuffer_texture_layer( target, slot, Some(&texture_object), *level as i32, *layer as i32, ); }); } AttachableImageRefKind::TextureCubeLevelFace { data, level, face } => { data.id().unwrap().with_value_unchecked(|texture_object| { gl.framebuffer_texture_2d( target, slot, face.id(), Some(&texture_object), *level as i32, ); }); } AttachableImageRefKind::Renderbuffer { data } => { data.id() .unwrap() .with_value_unchecked(|renderbuffer_object| { gl.framebuffer_renderbuffer( target, slot, Gl::RENDERBUFFER, Some(&renderbuffer_object), ); }); } } } } } #[derive(Clone, Hash, PartialEq)] pub(crate) enum AttachableImageRefKind { Texture2DLevel { data: Arc<Texture2DData>, level: u8, }, Texture2DArrayLevelLayer { data: Arc<Texture2DArrayData>, level: u8, layer: u16, }, Texture3DLevelLayer { data: Arc<Texture3DData>, level: u8, layer: u16, }, TextureCubeLevelFace { data: Arc<TextureCubeData>, level: u8, face: CubeFace, }, Renderbuffer { data: Arc<RenderbufferData>, }, }
pub(crate) fn from_texture_2d_level(image: &Texture2DLevel<'a, F>) -> Self where F: TextureFormat, { Attachment { data: AttachmentData { context_id: image.texture_data().context_id(), kind: AttachableImageRefKind::Texture2DLevel { data: image.texture_data().clone(), level: image.level() as u8, }, width: image.width(), height: image.height(), }, marker: marker::PhantomData, } }
function_block-full_function
[ { "content": "/// A helper trait for indexing a [LevelsMut].\n\n///\n\n/// See [LevelsMut::get_mut] and [LevelsMut::get_unchecked_mut].\n\npub trait LevelsMutIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if...
Rust
src/ffi/ffi.rs
ives9638/arrow2
b86508e67ca4b08c4544626f7bbe55cf5bd02961
use std::{ptr::NonNull, sync::Arc}; use crate::{ array::{buffers_children_dictionary, Array}, bitmap::{utils::bytes_for, Bitmap}, buffer::{ bytes::{Bytes, Deallocation}, Buffer, }, datatypes::{DataType, Field, PhysicalType}, error::{ArrowError, Result}, ffi::schema::get_field_child, types::NativeType, }; #[repr(C)] #[derive(Debug, Clone)] pub struct Ffi_ArrowArray { pub(crate) length: i64, pub(crate) null_count: i64, pub(crate) offset: i64, pub(crate) n_buffers: i64, pub(crate) n_children: i64, pub(crate) buffers: *mut *const ::std::os::raw::c_void, children: *mut *mut Ffi_ArrowArray, dictionary: *mut Ffi_ArrowArray, release: ::std::option::Option<unsafe extern "C" fn(arg1: *mut Ffi_ArrowArray)>, private_data: *mut ::std::os::raw::c_void, } impl Drop for Ffi_ArrowArray { fn drop(&mut self) { match self.release { None => (), Some(release) => unsafe { release(self) }, }; } } unsafe extern "C" fn c_release_array(array: *mut Ffi_ArrowArray) { if array.is_null() { return; } let array = &mut *array; let private = Box::from_raw(array.private_data as *mut PrivateData); for child in private.children_ptr.iter() { let _ = Box::from_raw(*child); } if let Some(ptr) = private.dictionary_ptr { let _ = Box::from_raw(ptr); } array.release = None; } #[allow(dead_code)] struct PrivateData { array: Arc<dyn Array>, buffers_ptr: Box<[*const std::os::raw::c_void]>, children_ptr: Box<[*mut Ffi_ArrowArray]>, dictionary_ptr: Option<*mut Ffi_ArrowArray>, } impl Ffi_ArrowArray { pub(crate) fn new(array: Arc<dyn Array>) -> Self { let (buffers, children, dictionary) = buffers_children_dictionary(array.as_ref()); let buffers_ptr = buffers .iter() .map(|maybe_buffer| match maybe_buffer { Some(b) => b.as_ptr() as *const std::os::raw::c_void, None => std::ptr::null(), }) .collect::<Box<[_]>>(); let n_buffers = buffers.len() as i64; let children_ptr = children .into_iter() .map(|child| Box::into_raw(Box::new(Ffi_ArrowArray::new(child)))) .collect::<Box<_>>(); let n_children = children_ptr.len() as i64; let dictionary_ptr = dictionary.map(|array| Box::into_raw(Box::new(Ffi_ArrowArray::new(array)))); let length = array.len() as i64; let null_count = array.null_count() as i64; let mut private_data = Box::new(PrivateData { array, buffers_ptr, children_ptr, dictionary_ptr, }); Self { length, null_count, offset: 0i64, n_buffers, n_children, buffers: private_data.buffers_ptr.as_mut_ptr(), children: private_data.children_ptr.as_mut_ptr(), dictionary: private_data.dictionary_ptr.unwrap_or(std::ptr::null_mut()), release: Some(c_release_array), private_data: Box::into_raw(private_data) as *mut ::std::os::raw::c_void, } } pub fn empty() -> Self { Self { length: 0, null_count: 0, offset: 0, n_buffers: 0, n_children: 0, buffers: std::ptr::null_mut(), children: std::ptr::null_mut(), dictionary: std::ptr::null_mut(), release: None, private_data: std::ptr::null_mut(), } } pub(crate) fn len(&self) -> usize { self.length as usize } pub(crate) fn offset(&self) -> usize { self.offset as usize } pub(crate) fn null_count(&self) -> usize { self.null_count as usize } } unsafe fn create_buffer<T: NativeType>( array: &Ffi_ArrowArray, data_type: &DataType, deallocation: Deallocation, index: usize, ) -> Result<Buffer<T>> { if array.buffers.is_null() { return Err(ArrowError::Ffi("The array buffers are null".to_string())); } let buffers = array.buffers as *mut *const u8; let len = buffer_len(array, data_type, index)?; assert!(index < array.n_buffers as usize); let ptr = *buffers.add(index); let ptr = NonNull::new(ptr as *mut T); let bytes = ptr .map(|ptr| Bytes::new(ptr, len, deallocation)) .ok_or_else(|| ArrowError::Ffi(format!("The buffer at position {} is null", index))); bytes.map(Buffer::from_bytes) } unsafe fn create_bitmap( array: &Ffi_ArrowArray, deallocation: Deallocation, index: usize, ) -> Result<Bitmap> { if array.buffers.is_null() { return Err(ArrowError::Ffi("The array buffers are null".to_string())); } let len = array.length as usize; let buffers = array.buffers as *mut *const u8; assert!(index < array.n_buffers as usize); let ptr = *buffers.add(index); let bytes_len = bytes_for(len); let ptr = NonNull::new(ptr as *mut u8); let bytes = ptr .map(|ptr| Bytes::new(ptr, bytes_len, deallocation)) .ok_or_else(|| { ArrowError::Ffi(format!( "The buffer {} is a null pointer and cannot be interpreted as a bitmap", index )) })?; Ok(Bitmap::from_bytes(bytes, len)) } fn buffer_len(array: &Ffi_ArrowArray, data_type: &DataType, i: usize) -> Result<usize> { Ok(match (data_type.to_physical_type(), i) { (PhysicalType::Utf8, 1) | (PhysicalType::LargeUtf8, 1) | (PhysicalType::Binary, 1) | (PhysicalType::LargeBinary, 1) | (PhysicalType::List, 1) | (PhysicalType::LargeList, 1) | (PhysicalType::Map, 1) => { array.length as usize + 1 } (PhysicalType::Utf8, 2) | (PhysicalType::Binary, 2) => { let len = buffer_len(array, data_type, 1)?; let offset_buffer = unsafe { *(array.buffers as *mut *const u8).add(1) }; let offset_buffer = offset_buffer as *const i32; (unsafe { *offset_buffer.add(len - 1) }) as usize } (PhysicalType::LargeUtf8, 2) | (PhysicalType::LargeBinary, 2) => { let len = buffer_len(array, data_type, 1)?; let offset_buffer = unsafe { *(array.buffers as *mut *const u8).add(1) }; let offset_buffer = offset_buffer as *const i64; (unsafe { *offset_buffer.add(len - 1) }) as usize } _ => array.length as usize, }) } fn create_child( array: &Ffi_ArrowArray, field: &Field, parent: Arc<ArrowArray>, index: usize, ) -> Result<ArrowArrayChild<'static>> { let field = get_field_child(field, index)?; assert!(index < array.n_children as usize); assert!(!array.children.is_null()); unsafe { let arr_ptr = *array.children.add(index); assert!(!arr_ptr.is_null()); let arr_ptr = &*arr_ptr; Ok(ArrowArrayChild::from_raw(arr_ptr, field, parent)) } } fn create_dictionary( array: &Ffi_ArrowArray, field: &Field, parent: Arc<ArrowArray>, ) -> Result<Option<ArrowArrayChild<'static>>> { if let DataType::Dictionary(_, values) = field.data_type() { let field = Field::new("", values.as_ref().clone(), true); assert!(!array.dictionary.is_null()); let array = unsafe { &*array.dictionary }; Ok(Some(ArrowArrayChild::from_raw(array, field, parent))) } else { Ok(None) } } pub trait ArrowArrayRef { fn deallocation(&self) -> Deallocation { Deallocation::Foreign(self.parent().clone()) } unsafe fn validity(&self) -> Result<Option<Bitmap>> { if self.array().null_count() == 0 { Ok(None) } else { create_bitmap(self.array(), self.deallocation(), 0).map(Some) } } unsafe fn buffer<T: NativeType>(&self, index: usize) -> Result<Buffer<T>> { create_buffer::<T>( self.array(), self.field().data_type(), self.deallocation(), index + 1, ) } unsafe fn bitmap(&self, index: usize) -> Result<Bitmap> { create_bitmap(self.array(), self.deallocation(), index + 1) } fn child(&self, index: usize) -> Result<ArrowArrayChild> { create_child(self.array(), self.field(), self.parent().clone(), index) } fn dictionary(&self) -> Result<Option<ArrowArrayChild>> { create_dictionary(self.array(), self.field(), self.parent().clone()) } fn parent(&self) -> &Arc<ArrowArray>; fn array(&self) -> &Ffi_ArrowArray; fn field(&self) -> &Field; } #[derive(Debug)] pub struct ArrowArray { array: Box<Ffi_ArrowArray>, field: Field, } impl ArrowArray { pub fn new(array: Box<Ffi_ArrowArray>, field: Field) -> Self { Self { array, field } } } impl ArrowArrayRef for Arc<ArrowArray> { fn field(&self) -> &Field { &self.field } fn parent(&self) -> &Arc<ArrowArray> { self } fn array(&self) -> &Ffi_ArrowArray { self.array.as_ref() } } #[derive(Debug)] pub struct ArrowArrayChild<'a> { array: &'a Ffi_ArrowArray, field: Field, parent: Arc<ArrowArray>, } impl<'a> ArrowArrayRef for ArrowArrayChild<'a> { fn field(&self) -> &Field { &self.field } fn parent(&self) -> &Arc<ArrowArray> { &self.parent } fn array(&self) -> &Ffi_ArrowArray { self.array } } impl<'a> ArrowArrayChild<'a> { fn from_raw(array: &'a Ffi_ArrowArray, field: Field, parent: Arc<ArrowArray>) -> Self { Self { array, field, parent, } } }
use std::{ptr::NonNull, sync::Arc}; use crate::{ array::{buffers_children_dictionary, Array}, bitmap::{utils::bytes_for, Bitmap}, buffer::{ bytes::{Bytes, Deallocation}, Buffer, }, datatypes::{DataType, Field, PhysicalType}, error::{ArrowError, Result}, ffi::schema::get_field_child, types::NativeType, }; #[repr(C)] #[derive(Debug, Clone)] pub struct Ffi_ArrowArray { pub(crate) length: i64, pub(crate) null_count: i64, pub(crate) offset: i64, pub(crate) n_buffers: i64, pub(crate) n_children: i64, pub(crate) buffers: *mut *const ::std::os::raw::c_void, children: *mut *mut Ffi_ArrowArray, dictionary: *mut Ffi_ArrowArray, release: ::std::option::Option<unsafe extern "C" fn(arg1: *mut Ffi_ArrowArray)>, private_data: *mut ::std::os::raw::c_void, } impl Drop for Ffi_ArrowArray { fn drop(&mut self) { match self.release { None => (), Some(release) => unsafe { release(self) }, }; } } unsafe extern "C" fn c_release_array(array: *mut Ffi_ArrowArray) { if array.is_null() { return; } let array = &mut *array; let private = Box::from_raw(array.private_data as *mut PrivateData); for child in private.children_ptr.iter() { let _ = Box::from_raw(*child); } if let Some(ptr) = private.dictionary_ptr { let _ = Box::from_raw(ptr); } array.release = None; } #[allow(dead_code)] struct PrivateData { array: Arc<dyn Array>, buffers_ptr: Box<[*const std::os::raw::c_void]>, children_ptr: Box<[*mut Ffi_ArrowArray]>, dictionary_ptr: Option<*mut Ffi_ArrowArray>, } impl Ffi_ArrowArray { pub(crate) fn new(array: Arc<dyn Array>) -> Self { let (buffers, children, dictionary) = buffers_children_dictionary(array.as_ref()); let buffers_ptr = buffers .iter() .map(|maybe_buffer| match maybe_buffer { Some(b) => b.as_ptr() as *const std::os::raw::c_void, None => std::ptr::null(), }) .collect::<Box<[_]>>(); let n_buffers = buffers.len() as i64; let children_ptr = children .into_iter() .map(|child| Box::into_raw(Box::new(Ffi_ArrowArray::new(child)))) .collect::<Box<_>>(); let n_children = children_ptr.len() as i64; let dictionary_ptr = dictionary.map(|array| Box::into_raw(Box::new(Ffi_ArrowArray::new(array)))); let length = array.len() as i64; let null_count = array.null_count() as i64; let mut private_data = Box::new(PrivateData { array, buffers_ptr, children_ptr, dictionary_ptr, }); Self { length, null_count, offset: 0i64, n_buffers, n_children, buffers: private_data.buffers_ptr.as_mut_ptr(), children: private_data.children_ptr.as_mut_ptr(), dictionary: private_data.dictionary_ptr.unwrap_or(std::ptr::null_mut()), release: Some(c_release_array), private_data: Box::into_raw(private_data) as *mut ::std::os::raw::c_void, } } pub fn empty() -> Self { Self { length: 0, null_count: 0, offset: 0, n_buffers: 0, n_children: 0, buffers: std::ptr::null_mut(), children: std::ptr::null_mut(), dictionary: std::ptr::null_mut(), release: None, private_data: std::ptr::null_mut(), } } pub(crate) fn len(&self) -> usize { self.length as usize } pub(crate) fn offset(&self) -> usize { self.offset as usize } pub(crate) fn null_count(&self) -> usize { self.null_count as usize } } unsafe fn create_buffer<T: NativeType>( array: &Ffi_ArrowArray, data_type: &DataType, deallocation: Deallocation, index: usize, ) -> Result<Buffer<T>> { if array.buffers.is_null() { return Err(ArrowError::Ffi("The array buffers are null".to_strin
unsafe fn create_bitmap( array: &Ffi_ArrowArray, deallocation: Deallocation, index: usize, ) -> Result<Bitmap> { if array.buffers.is_null() { return Err(ArrowError::Ffi("The array buffers are null".to_string())); } let len = array.length as usize; let buffers = array.buffers as *mut *const u8; assert!(index < array.n_buffers as usize); let ptr = *buffers.add(index); let bytes_len = bytes_for(len); let ptr = NonNull::new(ptr as *mut u8); let bytes = ptr .map(|ptr| Bytes::new(ptr, bytes_len, deallocation)) .ok_or_else(|| { ArrowError::Ffi(format!( "The buffer {} is a null pointer and cannot be interpreted as a bitmap", index )) })?; Ok(Bitmap::from_bytes(bytes, len)) } fn buffer_len(array: &Ffi_ArrowArray, data_type: &DataType, i: usize) -> Result<usize> { Ok(match (data_type.to_physical_type(), i) { (PhysicalType::Utf8, 1) | (PhysicalType::LargeUtf8, 1) | (PhysicalType::Binary, 1) | (PhysicalType::LargeBinary, 1) | (PhysicalType::List, 1) | (PhysicalType::LargeList, 1) | (PhysicalType::Map, 1) => { array.length as usize + 1 } (PhysicalType::Utf8, 2) | (PhysicalType::Binary, 2) => { let len = buffer_len(array, data_type, 1)?; let offset_buffer = unsafe { *(array.buffers as *mut *const u8).add(1) }; let offset_buffer = offset_buffer as *const i32; (unsafe { *offset_buffer.add(len - 1) }) as usize } (PhysicalType::LargeUtf8, 2) | (PhysicalType::LargeBinary, 2) => { let len = buffer_len(array, data_type, 1)?; let offset_buffer = unsafe { *(array.buffers as *mut *const u8).add(1) }; let offset_buffer = offset_buffer as *const i64; (unsafe { *offset_buffer.add(len - 1) }) as usize } _ => array.length as usize, }) } fn create_child( array: &Ffi_ArrowArray, field: &Field, parent: Arc<ArrowArray>, index: usize, ) -> Result<ArrowArrayChild<'static>> { let field = get_field_child(field, index)?; assert!(index < array.n_children as usize); assert!(!array.children.is_null()); unsafe { let arr_ptr = *array.children.add(index); assert!(!arr_ptr.is_null()); let arr_ptr = &*arr_ptr; Ok(ArrowArrayChild::from_raw(arr_ptr, field, parent)) } } fn create_dictionary( array: &Ffi_ArrowArray, field: &Field, parent: Arc<ArrowArray>, ) -> Result<Option<ArrowArrayChild<'static>>> { if let DataType::Dictionary(_, values) = field.data_type() { let field = Field::new("", values.as_ref().clone(), true); assert!(!array.dictionary.is_null()); let array = unsafe { &*array.dictionary }; Ok(Some(ArrowArrayChild::from_raw(array, field, parent))) } else { Ok(None) } } pub trait ArrowArrayRef { fn deallocation(&self) -> Deallocation { Deallocation::Foreign(self.parent().clone()) } unsafe fn validity(&self) -> Result<Option<Bitmap>> { if self.array().null_count() == 0 { Ok(None) } else { create_bitmap(self.array(), self.deallocation(), 0).map(Some) } } unsafe fn buffer<T: NativeType>(&self, index: usize) -> Result<Buffer<T>> { create_buffer::<T>( self.array(), self.field().data_type(), self.deallocation(), index + 1, ) } unsafe fn bitmap(&self, index: usize) -> Result<Bitmap> { create_bitmap(self.array(), self.deallocation(), index + 1) } fn child(&self, index: usize) -> Result<ArrowArrayChild> { create_child(self.array(), self.field(), self.parent().clone(), index) } fn dictionary(&self) -> Result<Option<ArrowArrayChild>> { create_dictionary(self.array(), self.field(), self.parent().clone()) } fn parent(&self) -> &Arc<ArrowArray>; fn array(&self) -> &Ffi_ArrowArray; fn field(&self) -> &Field; } #[derive(Debug)] pub struct ArrowArray { array: Box<Ffi_ArrowArray>, field: Field, } impl ArrowArray { pub fn new(array: Box<Ffi_ArrowArray>, field: Field) -> Self { Self { array, field } } } impl ArrowArrayRef for Arc<ArrowArray> { fn field(&self) -> &Field { &self.field } fn parent(&self) -> &Arc<ArrowArray> { self } fn array(&self) -> &Ffi_ArrowArray { self.array.as_ref() } } #[derive(Debug)] pub struct ArrowArrayChild<'a> { array: &'a Ffi_ArrowArray, field: Field, parent: Arc<ArrowArray>, } impl<'a> ArrowArrayRef for ArrowArrayChild<'a> { fn field(&self) -> &Field { &self.field } fn parent(&self) -> &Arc<ArrowArray> { &self.parent } fn array(&self) -> &Ffi_ArrowArray { self.array } } impl<'a> ArrowArrayChild<'a> { fn from_raw(array: &'a Ffi_ArrowArray, field: Field, parent: Arc<ArrowArray>) -> Self { Self { array, field, parent, } } }
g())); } let buffers = array.buffers as *mut *const u8; let len = buffer_len(array, data_type, index)?; assert!(index < array.n_buffers as usize); let ptr = *buffers.add(index); let ptr = NonNull::new(ptr as *mut T); let bytes = ptr .map(|ptr| Bytes::new(ptr, len, deallocation)) .ok_or_else(|| ArrowError::Ffi(format!("The buffer at position {} is null", index))); bytes.map(Buffer::from_bytes) }
function_block-function_prefixed
[ { "content": "/// Shifts array by defined number of items (to left or right)\n\n/// A positive value for `offset` shifts the array to the right\n\n/// a negative value shifts the array to the left.\n\n/// # Examples\n\n/// ```\n\n/// use arrow2::array::Int32Array;\n\n/// use arrow2::compute::window::shift;\n\n/...
Rust
flow-rs/src/node/transform.rs
MegEngine/MegFlow
4bbf15acc21fb1f51e95311e28fb0a10fe4a91d3
/** * \file flow-rs/src/node/transform.rs * MegFlow is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2019-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ use crate::rt; use anyhow::Result; use flow_rs::prelude::*; use toml::value::Table; #[inputs(inp)] #[outputs(out)] #[derive(Node, Actor, Default)] struct Transform {} impl Transform { fn new(_name: String, _args: &Table) -> Transform { Default::default() } async fn initialize(&mut self, _: ResourceCollection) {} async fn finalize(&mut self) {} async fn exec(&mut self, _: &Context) -> Result<()> { if let Ok(msg) = self.inp.recv_any().await { self.out.send_any(msg).await.ok(); } Ok(()) } } node_register!("Transform", Transform); #[inputs(inp)] #[outputs(out:dyn)] #[derive(Node, Default)] struct DynOutTransform {} impl DynOutTransform { fn new(_name: String, _args: &Table) -> DynOutTransform { Default::default() } } impl Actor for DynOutTransform { fn start( mut self: Box<Self>, _: Context, _: ResourceCollection, ) -> rt::task::JoinHandle<Result<()>> { let (s, r) = rt::channel::unbounded(); rt::task::spawn(async move { while let Ok((_, out)) = self.out.fetch().await { let inp = self.inp.clone(); s.send(rt::task::spawn(async move { let mut empty_n = 0; loop { while let Ok(msg) = inp.recv_any().await { out.send_any(msg).await.ok(); } if inp.is_closed() { break; } let n = inp.empty_n(); for _ in empty_n..n { out.send_any(DummyEnvelope {}.seal()).await.ok(); } empty_n = n; } })) .await .ok(); } }); rt::task::spawn(async move { while let Ok(handle) = r.recv().await { handle.await; } Ok(()) }) } } node_register!("DynOutTransform", DynOutTransform); #[inputs(inp: dyn)] #[outputs(out)] #[derive(Node, Default)] struct DynInTransform {} impl DynInTransform { fn new(_name: String, _args: &Table) -> DynInTransform { Default::default() } } impl Actor for DynInTransform { fn start( self: Box<Self>, _: Context, _: ResourceCollection, ) -> rt::task::JoinHandle<Result<()>> { let (s, r) = rt::channel::unbounded(); rt::task::spawn(async move { while let Ok((_, inp)) = self.inp.fetch().await { let out = self.out.clone(); s.send(rt::task::spawn(async move { while !inp.is_closed() { while let Ok(msg) = inp.recv_any().await { out.send_any(msg).await.ok(); } assert!( inp.empty_n() == 0, "DynInTransform is not supported in a shared subgraph" ); } })) .await .ok(); } }); rt::task::spawn(async move { while let Ok(handle) = r.recv().await { handle.await; } Ok(()) }) } } node_register!("DynInTransform", DynInTransform);
/** * \file flow-rs/src/node/transform.rs * MegFlow is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2019-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ use crate::rt; use anyhow::Result; use flow_rs::prelude::*; use toml::value::Table; #[inputs(inp)] #[outputs(out)] #[derive(Node, Actor, Default)] struct Transform {} impl Transform { fn new(_name: String, _args: &Table) -> Transform { Default::default() } async fn initialize(&mut self, _: ResourceCollection) {} async fn finalize(&mut self) {}
} node_register!("Transform", Transform); #[inputs(inp)] #[outputs(out:dyn)] #[derive(Node, Default)] struct DynOutTransform {} impl DynOutTransform { fn new(_name: String, _args: &Table) -> DynOutTransform { Default::default() } } impl Actor for DynOutTransform { fn start( mut self: Box<Self>, _: Context, _: ResourceCollection, ) -> rt::task::JoinHandle<Result<()>> { let (s, r) = rt::channel::unbounded(); rt::task::spawn(async move { while let Ok((_, out)) = self.out.fetch().await { let inp = self.inp.clone(); s.send(rt::task::spawn(async move { let mut empty_n = 0; loop { while let Ok(msg) = inp.recv_any().await { out.send_any(msg).await.ok(); } if inp.is_closed() { break; } let n = inp.empty_n(); for _ in empty_n..n { out.send_any(DummyEnvelope {}.seal()).await.ok(); } empty_n = n; } })) .await .ok(); } }); rt::task::spawn(async move { while let Ok(handle) = r.recv().await { handle.await; } Ok(()) }) } } node_register!("DynOutTransform", DynOutTransform); #[inputs(inp: dyn)] #[outputs(out)] #[derive(Node, Default)] struct DynInTransform {} impl DynInTransform { fn new(_name: String, _args: &Table) -> DynInTransform { Default::default() } } impl Actor for DynInTransform { fn start( self: Box<Self>, _: Context, _: ResourceCollection, ) -> rt::task::JoinHandle<Result<()>> { let (s, r) = rt::channel::unbounded(); rt::task::spawn(async move { while let Ok((_, inp)) = self.inp.fetch().await { let out = self.out.clone(); s.send(rt::task::spawn(async move { while !inp.is_closed() { while let Ok(msg) = inp.recv_any().await { out.send_any(msg).await.ok(); } assert!( inp.empty_n() == 0, "DynInTransform is not supported in a shared subgraph" ); } })) .await .ok(); } }); rt::task::spawn(async move { while let Ok(handle) = r.recv().await { handle.await; } Ok(()) }) } } node_register!("DynInTransform", DynInTransform);
async fn exec(&mut self, _: &Context) -> Result<()> { if let Ok(msg) = self.inp.recv_any().await { self.out.send_any(msg).await.ok(); } Ok(()) }
function_block-full_function
[ { "content": "#[pyfunction]\n\nfn version() -> &'static str {\n\n env!(\"CARGO_PKG_VERSION\")\n\n}\n\n\n\n#[pymethods]\n\nimpl Graph {\n\n fn wait(&mut self, py: Python) {\n\n self.inps.clear();\n\n self.outs.clear();\n\n if let Some(graph) = self.graph.take() {\n\n graph.s...
Rust
crates/ruma-events/src/room/encrypted/relation_serde.rs
MTRNord/ruma
653e4c4838fb3e5809573ce0a7e763547d5f20e4
#[cfg(feature = "unstable-pre-spec")] use ruma_identifiers::EventId; use serde::{ser::SerializeStruct as _, Deserialize, Deserializer, Serialize, Serializer}; #[cfg(feature = "unstable-pre-spec")] use super::{Annotation, Reference, Replacement}; use super::{InReplyTo, Relation}; #[cfg(feature = "unstable-pre-spec")] use crate::room::message::MessageEventContent; pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Relation>, D::Error> where D: Deserializer<'de>, { fn convert_relation(ev: EventWithRelatesToJsonRepr) -> Option<Relation> { if let Some(in_reply_to) = ev.relates_to.in_reply_to { return Some(Relation::Reply { in_reply_to }); } #[cfg(feature = "unstable-pre-spec")] if let Some(relation) = ev.relates_to.relation { let relation = match relation { RelationJsonRepr::Annotation(a) => Relation::Annotation(a), RelationJsonRepr::Reference(r) => Relation::Reference(r), RelationJsonRepr::Replacement(ReplacementJsonRepr { event_id }) => { let new_content = ev.new_content?; Relation::Replacement(Replacement { event_id, new_content }) } RelationJsonRepr::Unknown => return None, }; return Some(relation); } None } EventWithRelatesToJsonRepr::deserialize(deserializer).map(convert_relation) } pub fn serialize<S>(relation: &Option<Relation>, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let relation = match relation { Some(rel) => rel, None => return serializer.serialize_struct("NoRelation", 0)?.end(), }; let json_repr = match relation { #[cfg(feature = "unstable-pre-spec")] Relation::Annotation(r) => EventWithRelatesToJsonRepr::new(RelatesToJsonRepr { relation: Some(RelationJsonRepr::Annotation(r.clone())), ..Default::default() }), #[cfg(feature = "unstable-pre-spec")] Relation::Reference(r) => EventWithRelatesToJsonRepr::new(RelatesToJsonRepr { relation: Some(RelationJsonRepr::Reference(r.clone())), ..Default::default() }), #[cfg(feature = "unstable-pre-spec")] Relation::Replacement(Replacement { event_id, new_content }) => { EventWithRelatesToJsonRepr { relates_to: RelatesToJsonRepr { relation: Some(RelationJsonRepr::Replacement(ReplacementJsonRepr { event_id: event_id.clone(), })), ..Default::default() }, new_content: Some(new_content.clone()), } } Relation::Reply { in_reply_to } => EventWithRelatesToJsonRepr::new(RelatesToJsonRepr { in_reply_to: Some(in_reply_to.clone()), ..Default::default() }), }; json_repr.serialize(serializer) } #[derive(Deserialize, Serialize)] struct EventWithRelatesToJsonRepr { #[serde(rename = "m.relates_to", default, skip_serializing_if = "RelatesToJsonRepr::is_empty")] relates_to: RelatesToJsonRepr, #[cfg(feature = "unstable-pre-spec")] #[serde(rename = "m.new_content", skip_serializing_if = "Option::is_none")] new_content: Option<Box<MessageEventContent>>, } impl EventWithRelatesToJsonRepr { fn new(relates_to: RelatesToJsonRepr) -> Self { Self { relates_to, #[cfg(feature = "unstable-pre-spec")] new_content: None, } } } #[derive(Default, Deserialize, Serialize)] struct RelatesToJsonRepr { #[serde(rename = "m.in_reply_to", skip_serializing_if = "Option::is_none")] in_reply_to: Option<InReplyTo>, #[cfg(feature = "unstable-pre-spec")] #[serde(flatten, skip_serializing_if = "Option::is_none")] relation: Option<RelationJsonRepr>, } impl RelatesToJsonRepr { fn is_empty(&self) -> bool { #[cfg(not(feature = "unstable-pre-spec"))] { self.in_reply_to.is_none() } #[cfg(feature = "unstable-pre-spec")] { self.in_reply_to.is_none() && self.relation.is_none() } } } #[derive(Clone, Deserialize, Serialize)] #[cfg(feature = "unstable-pre-spec")] #[serde(tag = "rel_type")] enum RelationJsonRepr { #[serde(rename = "m.annotation")] Annotation(Annotation), #[serde(rename = "m.reference")] Reference(Reference), #[serde(rename = "m.replace")] Replacement(ReplacementJsonRepr), #[serde(other)] Unknown, } #[derive(Clone, Deserialize, Serialize)] #[cfg(feature = "unstable-pre-spec")] struct ReplacementJsonRepr { event_id: EventId, }
#[cfg(feature = "unstable-pre-spec")] use ruma_identifiers::EventId; use serde::{ser::SerializeStruct as _, Deserialize, Deserializer, Serialize, Serializer}; #[cfg(feature = "unstable-pre-spec")] use super::{Annotation, Reference, Replacement}; use super::{InReplyTo, Relation}; #[cfg(feature = "unstable-pre-spec")] use crate::room::message::MessageEventContent; pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Relation>, D::Error> where D: Deserializer<'de>, { fn convert_relation(ev: EventWithRelatesToJsonRepr) -> Option<Relation> { if let Some(in_reply_to) = ev.relates_to.in_reply_to { return Some(Relation::Reply { in_reply_to }); } #[cfg(feature = "unstable-pre-spec")] if let Some(relation) = ev.relates_to.relation { let relation = match relation { RelationJsonRepr::Annotation(a) => Relation::Annotation(a), RelationJsonRepr::Reference(r) => Relation::Reference(r), RelationJsonRepr::Replacement(ReplacementJsonRepr { event_id }) => { let new_content = ev.new_content?; Relation::Replacement(Replacement { event_id, new_content }) } RelationJsonRepr::Unknown => return None, }; return Some(relation); } None } EventWithRelatesToJsonRepr::deserialize(deserializer).map(convert_relation) } pub fn serialize<S>(relation: &Option<Relation>, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let relation = match relation { Some(rel) => rel, None => return serializer.serialize_struct("NoRelation", 0)?.end(), }; let json_repr = match relati
, #[serde(rename = "m.reference")] Reference(Reference), #[serde(rename = "m.replace")] Replacement(ReplacementJsonRepr), #[serde(other)] Unknown, } #[derive(Clone, Deserialize, Serialize)] #[cfg(feature = "unstable-pre-spec")] struct ReplacementJsonRepr { event_id: EventId, }
on { #[cfg(feature = "unstable-pre-spec")] Relation::Annotation(r) => EventWithRelatesToJsonRepr::new(RelatesToJsonRepr { relation: Some(RelationJsonRepr::Annotation(r.clone())), ..Default::default() }), #[cfg(feature = "unstable-pre-spec")] Relation::Reference(r) => EventWithRelatesToJsonRepr::new(RelatesToJsonRepr { relation: Some(RelationJsonRepr::Reference(r.clone())), ..Default::default() }), #[cfg(feature = "unstable-pre-spec")] Relation::Replacement(Replacement { event_id, new_content }) => { EventWithRelatesToJsonRepr { relates_to: RelatesToJsonRepr { relation: Some(RelationJsonRepr::Replacement(ReplacementJsonRepr { event_id: event_id.clone(), })), ..Default::default() }, new_content: Some(new_content.clone()), } } Relation::Reply { in_reply_to } => EventWithRelatesToJsonRepr::new(RelatesToJsonRepr { in_reply_to: Some(in_reply_to.clone()), ..Default::default() }), }; json_repr.serialize(serializer) } #[derive(Deserialize, Serialize)] struct EventWithRelatesToJsonRepr { #[serde(rename = "m.relates_to", default, skip_serializing_if = "RelatesToJsonRepr::is_empty")] relates_to: RelatesToJsonRepr, #[cfg(feature = "unstable-pre-spec")] #[serde(rename = "m.new_content", skip_serializing_if = "Option::is_none")] new_content: Option<Box<MessageEventContent>>, } impl EventWithRelatesToJsonRepr { fn new(relates_to: RelatesToJsonRepr) -> Self { Self { relates_to, #[cfg(feature = "unstable-pre-spec")] new_content: None, } } } #[derive(Default, Deserialize, Serialize)] struct RelatesToJsonRepr { #[serde(rename = "m.in_reply_to", skip_serializing_if = "Option::is_none")] in_reply_to: Option<InReplyTo>, #[cfg(feature = "unstable-pre-spec")] #[serde(flatten, skip_serializing_if = "Option::is_none")] relation: Option<RelationJsonRepr>, } impl RelatesToJsonRepr { fn is_empty(&self) -> bool { #[cfg(not(feature = "unstable-pre-spec"))] { self.in_reply_to.is_none() } #[cfg(feature = "unstable-pre-spec")] { self.in_reply_to.is_none() && self.relation.is_none() } } } #[derive(Clone, Deserialize, Serialize)] #[cfg(feature = "unstable-pre-spec")] #[serde(tag = "rel_type")] enum RelationJsonRepr { #[serde(rename = "m.annotation")] Annotation(Annotation)
random
[ { "content": "pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Relation>, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n fn convert_relation(ev: EventWithRelatesToJsonRepr) -> Option<Relation> {\n\n if let Some(in_reply_to) = ev.relates_to.in_reply_to {\n\n return Some...
Rust
meteora-server/src/raft/server.rs
meteora-kvs/meteora
3dc67f72364ba17540970dca43559f12d1a6d929
use std::collections::HashMap; use std::sync::mpsc; use std::sync::mpsc::Sender; use std::time::Duration; use futures::Future; use grpcio::{RpcContext, UnarySink}; use log::*; use raft::eraftpb::{ConfChange, Message}; use meteora_proto::proto::common::{NodeAddress, Null, State}; use meteora_proto::proto::raft::{AddressState, ChangeReply, StatusReply}; use meteora_proto::proto::raft_grpc::RaftService; use crate::raft::config; #[derive(Clone)] pub struct RaftServer { pub sender: Sender<config::Msg>, seq: u64, node_id: u64, } impl RaftServer { pub fn new(sender: Sender<config::Msg>, node_id: u64) -> RaftServer { RaftServer { sender, seq: 0, node_id, } } } impl RaftService for RaftServer { fn status(&mut self, ctx: RpcContext, _req: Null, sink: UnarySink<StatusReply>) { let (s1, r1) = mpsc::channel(); let sender = self.sender.clone(); let node_id = self.node_id; sender .send(config::Msg::Read { cb: Box::new( move |leader_id: i32, addresses: HashMap<u64, NodeAddress>| { let mut reply = StatusReply::new(); reply.set_state(State::OK); if leader_id >= 0 { reply.set_leader_id(leader_id as u64); } else { reply.set_leader_id(node_id); } reply.set_address_map(addresses); s1.send(reply).expect("callback channel closed"); }, ), }) .unwrap(); let reply = match r1.recv_timeout(Duration::from_secs(2)) { Ok(r) => r, Err(e) => { error!("error: {:?}", e); let mut r = StatusReply::new(); r.set_state(State::IO_ERROR); r } }; let f = sink .success(reply.clone()) .map_err(move |err| error!("failed to reply: {:?}", err)); ctx.spawn(f); } fn change_config(&mut self, ctx: RpcContext, req: ConfChange, sink: UnarySink<ChangeReply>) { let (s1, r1) = mpsc::channel(); let sender = self.sender.clone(); let seq = self.seq; let node_id = self.node_id; self.seq += 1; sender .send(config::Msg::ConfigChange { seq, change: req, cb: Box::new( move |leader_id: i32, addresses: HashMap<u64, NodeAddress>| { let mut reply = ChangeReply::new(); if leader_id >= 0 { reply.set_state(State::WRONG_LEADER); reply.set_leader_id(leader_id as u64); } else { reply.set_state(State::OK); reply.set_leader_id(node_id); } reply.set_address_map(addresses); s1.send(reply).expect("callback channel closed"); }, ), }) .unwrap(); let reply = match r1.recv_timeout(Duration::from_secs(2)) { Ok(r) => r, Err(e) => { error!("error: {:?}", e); let mut r = ChangeReply::new(); r.set_state(State::IO_ERROR); r } }; let f = sink .success(reply.clone()) .map_err(move |err| error!("failed to reply: {:?}", err)); ctx.spawn(f); } fn send_msg(&mut self, _ctx: RpcContext, req: Message, _sink: ::grpcio::UnarySink<Null>) { let sender = self.sender.clone(); sender.send(config::Msg::Raft(req)).unwrap(); } fn send_address(&mut self, _ctx: RpcContext, req: AddressState, _sink: UnarySink<Null>) { let sender = self.sender.clone(); sender.send(config::Msg::Address(req)).unwrap(); } }
use std::collections::HashMap; use std::sync::mpsc; use std::sync::mpsc::Sender; use std::time::Duration; use futures::Future; use grpcio::{RpcContext, UnarySink}; use log::*; use raft::eraftpb::{ConfChange, Message}; use meteora_proto::proto::common::{NodeAddress, Null, State}; use meteora_proto::proto::raft::{AddressState, ChangeReply, StatusReply}; use meteora_proto::proto::raft_grpc::RaftService; use crate::raft::config; #[derive(Clone)] pub struct RaftServer { pub sender: Sender<config::Msg>, seq: u64, node_id: u64, } impl RaftServer { pub fn new(sender: Sender<config::Msg>, node_id: u64) -> RaftServer { RaftServer { sender, seq: 0, node_id, } } } impl RaftService for RaftServer { fn status(&mut self, ctx: RpcContext, _req: Null, sink: UnarySink<StatusReply>) { let (s1, r1) = mpsc::channel(); let sender = self.sender.clone(); let node_id = self.node_id; sender .send(config::Msg::Read { cb: Box::new( move |leader_id: i32, addresses: HashMap<u64, NodeAddress>| { let mut reply = StatusReply::new(); reply.set_state(State::OK); if leader_id >= 0 { reply.set_leader_id(leader_id as u64); } else { reply.set_leader_id(node_id); } reply.set_address_map(addresses); s1.send(reply).expect("callback channel closed"); }, ), }) .unwrap(); let reply = match r1.recv_timeout(Duration::from_secs(2)) { Ok(r) => r, Err(e) => { error!("error: {:?}", e); let mut r = StatusReply::new(); r.set_state(State::IO_ERROR); r } }; let f = sink .success(reply.clone()) .map_err(move |err| error!("failed to reply: {:?}", err)); ctx.spawn(f); } fn change_config(&mut self, ctx: RpcContext, req: ConfChange, sink: UnarySink<ChangeReply>) { let (s1, r1) = m
self.seq += 1; sender .send(config::Msg::ConfigChange { seq, change: req, cb: Box::new( move |leader_id: i32, addresses: HashMap<u64, NodeAddress>| { let mut reply = ChangeReply::new(); if leader_id >= 0 { reply.set_state(State::WRONG_LEADER); reply.set_leader_id(leader_id as u64); } else { reply.set_state(State::OK); reply.set_leader_id(node_id); } reply.set_address_map(addresses); s1.send(reply).expect("callback channel closed"); }, ), }) .unwrap(); let reply = match r1.recv_timeout(Duration::from_secs(2)) { Ok(r) => r, Err(e) => { error!("error: {:?}", e); let mut r = ChangeReply::new(); r.set_state(State::IO_ERROR); r } }; let f = sink .success(reply.clone()) .map_err(move |err| error!("failed to reply: {:?}", err)); ctx.spawn(f); } fn send_msg(&mut self, _ctx: RpcContext, req: Message, _sink: ::grpcio::UnarySink<Null>) { let sender = self.sender.clone(); sender.send(config::Msg::Raft(req)).unwrap(); } fn send_address(&mut self, _ctx: RpcContext, req: AddressState, _sink: UnarySink<Null>) { let sender = self.sender.clone(); sender.send(config::Msg::Address(req)).unwrap(); } }
psc::channel(); let sender = self.sender.clone(); let seq = self.seq; let node_id = self.node_id;
random
[ { "content": "type ProposeCallback = Box<dyn Fn(i32, HashMap<u64, NodeAddress>) + Send>;\n\n\n\npub enum Msg {\n\n Propose {\n\n seq: u64,\n\n op: Op,\n\n cb: ProposeCallback,\n\n },\n\n ConfigChange {\n\n seq: u64,\n\n change: ConfChange,\n\n cb: ProposeCallba...
Rust
crates/irust/src/irust/script/mod.rs
i10416/IRust
6faff9bb1fc52597cdd4698e1179932885da375c
use crossterm::event::Event; use irust_api::{Command, GlobalVariables}; use self::script4::ScriptManager4; use super::options::Options; pub mod script4; pub trait Script { fn input_prompt(&mut self, _global_variables: &GlobalVariables) -> Option<String>; fn get_output_prompt(&mut self, _global_variables: &GlobalVariables) -> Option<String>; fn before_compiling(&mut self, _global_variables: &GlobalVariables) -> Option<()>; fn input_event_hook( &mut self, _global_variables: &GlobalVariables, _event: Event, ) -> Option<Command>; fn after_compiling(&mut self, _global_variables: &GlobalVariables) -> Option<()>; fn output_event_hook( &mut self, _input: &str, _global_variables: &GlobalVariables, ) -> Option<Command>; fn list(&self) -> Option<String>; fn activate(&mut self, _script: &str) -> Result<Option<Command>, &'static str>; fn deactivate(&mut self, _script: &str) -> Result<Option<Command>, &'static str>; fn trigger_set_title_hook(&mut self) -> Option<String>; fn trigger_set_msg_hook(&mut self) -> Option<String>; fn startup_cmds(&mut self) -> Vec<Result<Option<Command>, rscript::Error>>; fn shutdown_cmds(&mut self) -> Vec<Result<Option<Command>, rscript::Error>>; } impl super::IRust { pub fn update_input_prompt(&mut self) { if let Some(ref mut script_mg) = self.script_mg { if let Some(prompt) = script_mg.input_prompt(&self.global_variables) { self.printer.set_prompt(prompt); } } } pub fn get_output_prompt(&mut self) -> String { if let Some(ref mut script_mg) = self.script_mg { if let Some(prompt) = script_mg.get_output_prompt(&self.global_variables) { return prompt; } } self.options.output_prompt.clone() } pub fn before_compiling_hook(&mut self) { if let Some(ref mut script_mg) = self.script_mg { script_mg.before_compiling(&self.global_variables); } } pub fn input_event_hook(&mut self, event: Event) -> Option<Command> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.input_event_hook(&self.global_variables, event); } None } pub fn after_compiling_hook(&mut self) { if let Some(ref mut script_mg) = self.script_mg { script_mg.after_compiling(&self.global_variables); } } pub fn output_event_hook(&mut self, input: &str) -> Option<Command> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.output_event_hook(input, &self.global_variables); } None } pub fn trigger_set_title_hook(&mut self) -> Option<String> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.trigger_set_title_hook(); } None } pub fn trigger_set_msg_hook(&mut self) -> Option<String> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.trigger_set_msg_hook(); } None } pub fn scripts_list(&self) -> Option<String> { if let Some(ref script_mg) = self.script_mg { return script_mg.list(); } None } pub fn activate_script(&mut self, script: &str) -> Result<Option<Command>, &'static str> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.activate(script); } Ok(None) } pub fn deactivate_script(&mut self, script: &str) -> Result<Option<Command>, &'static str> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.deactivate(script); } Ok(None) } pub fn choose_script_mg(options: &Options) -> Option<Box<dyn Script>> { if options.activate_scripting { ScriptManager4::new().map(|script_mg| Box::new(script_mg) as Box<dyn Script>) } else { None } } pub fn update_script_state(&mut self) { self.global_variables.prompt_position = self.printer.cursor.starting_pos(); self.global_variables.cursor_position = self.printer.cursor.current_pos(); self.global_variables.is_racer_suggestion_active = self .racer .as_ref() .and_then(|r| r.active_suggestion.as_ref()) .is_some(); } pub fn run_scripts_startup_cmds(&mut self) -> super::Result<()> { if let Some(ref mut script_mg) = self.script_mg { for cmd in script_mg.startup_cmds() { if let Some(cmd) = cmd? { self.execute(cmd)?; } } } Ok(()) } pub fn run_scripts_shutdown_cmds(&mut self) -> super::Result<()> { if let Some(ref mut script_mg) = self.script_mg { for cmd in script_mg.shutdown_cmds() { if let Some(cmd) = cmd? { self.execute(cmd)?; } } } Ok(()) } }
use crossterm::event::Event; use irust_api::{Command, GlobalVariables}; use self::script4::ScriptManager4; use super::options::Options; pub mod script4; pub trait Script { fn input_prompt(&mut self, _global_variables: &GlobalVariables) -> Option<String>; fn get_output_prompt(&mut self, _global_variables: &GlobalVariables) -> Option<String>; fn before_compiling(&mut self, _global_variables: &GlobalVariables) -> Option<()>; fn input_event_hook( &mut self, _global_variables: &GlobalVariables, _event: Event, ) -> Option<Command>; fn after_compiling(&mut self, _global_variables: &GlobalVariables) -> Option<()>; fn output_event_hook( &mut self, _input: &str, _global_variables: &GlobalVariables, ) -> Option<Command>; fn list(&self) -> Option<String>; fn activate(&mut self, _script: &str) -> Result<Option<Command>, &'static str>; fn deactivate(&mut self, _script: &str) -> Result<Option<Command>, &'static str>; fn trigger_set_title_hook(&mut self) -> Option<String>; fn trigger_set_msg_hook(&mut self) -> Option<String>; fn startup_cmds(&mut self) -> Vec<Result<Option<Command>, rscript::Error>>; fn shutdown_cmds(&mut self) -> Vec<Result<Option<Command>, rscript::Error>>; } impl super::IRust { pub fn update_input_prompt(&mut self) { if let Some(ref mut script_mg) = self.script_mg { if let Some(prompt) = script_mg.input_prompt(&self.global_variables) { self.printer.set_prompt(prompt); } } } pub fn get_output_prompt(&mut self) -> String { if let Some(ref mut script_mg) = self.script_mg { if let Some(prompt) = script_mg.get_output_prompt(&self.global_variables) { return prompt; } } self.options.output_prompt.clone() } pub fn before_compiling_hook(&mut self) { if let Some(ref mut script_mg) = self.script_mg { script_mg.before_compiling(&self.global_variables); } } pub fn input_event_hook(&mut self, event: Event) -> Option<Command> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.input_event_hook(&self.global_variables, event); } None } pub fn after_compiling_hook(&mut self) { if let Some(ref mut script_mg) = self.script_mg { script_mg.after_compiling(&self.global_variables); } } pub fn output_event_hook(&mut self, input: &str) -> Option<Command> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.output_event_hook(input, &self.global_variables); } None } pub fn trigger_set_title_hook(&mut self) -> Option<String> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.trigger_set_title_hook(); } None } pub fn trigger_set_msg_hook(&mut self) -> Option<String> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.trigger_set_msg_hook(); } None } pub fn scripts_list(&self) -> Option<String> { if let Some(ref script_mg) = self.script_mg { return script_mg.list(); } None } pub fn activate_script(&mut self, script: &str) -> Result<Option<Comman
pub fn deactivate_script(&mut self, script: &str) -> Result<Option<Command>, &'static str> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.deactivate(script); } Ok(None) } pub fn choose_script_mg(options: &Options) -> Option<Box<dyn Script>> { if options.activate_scripting { ScriptManager4::new().map(|script_mg| Box::new(script_mg) as Box<dyn Script>) } else { None } } pub fn update_script_state(&mut self) { self.global_variables.prompt_position = self.printer.cursor.starting_pos(); self.global_variables.cursor_position = self.printer.cursor.current_pos(); self.global_variables.is_racer_suggestion_active = self .racer .as_ref() .and_then(|r| r.active_suggestion.as_ref()) .is_some(); } pub fn run_scripts_startup_cmds(&mut self) -> super::Result<()> { if let Some(ref mut script_mg) = self.script_mg { for cmd in script_mg.startup_cmds() { if let Some(cmd) = cmd? { self.execute(cmd)?; } } } Ok(()) } pub fn run_scripts_shutdown_cmds(&mut self) -> super::Result<()> { if let Some(ref mut script_mg) = self.script_mg { for cmd in script_mg.shutdown_cmds() { if let Some(cmd) = cmd? { self.execute(cmd)?; } } } Ok(()) } }
d>, &'static str> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.activate(script); } Ok(None) }
function_block-function_prefixed
[ { "content": "fn _remove_main(script: &str) -> String {\n\n const MAIN_FN: &str = \"fn main() {\";\n\n\n\n let mut script = remove_comments(script);\n\n\n\n let main_start = match script.find(MAIN_FN) {\n\n Some(idx) if _balanced_quotes(&script[..idx]) => idx,\n\n _ => return script,\n\n ...
Rust
src/stage_spec.rs
Isaac-Lozano/sa2_piece_gen
fd99d4cdd8b1f2e5d08072a962b8e686d8462153
use std::fs::File; use std::io::{Read, Seek, SeekFrom}; use std::path::Path; use serde_derive::{Serialize, Deserialize}; #[cfg(windows)] use process_reader::ProcessHandle; use byteorder::{ReadBytesExt, BE}; use crate::vector::Vector; use crate::rng::Rng; use crate::Platform; #[derive(Clone, Copy, Debug, Serialize, Deserialize)] pub struct Emerald { pub id: u16, pub position: Vector, } impl Default for Emerald { fn default() -> Emerald { Emerald { id: 0xFF00, position: Vector::default(), } } } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct StageSpec { pub slot1_pieces: Vec<Emerald>, pub slot2_pieces: Vec<Emerald>, pub slot3_pieces: Vec<Emerald>, pub enemy_pieces: Vec<Emerald>, pub pre_calls: u32, } impl StageSpec { #[cfg(windows)] pub fn from_process<P>(process_name: &str) -> StageSpec where P: Platform, { let p_handle = ProcessHandle::from_name_filter(|s| s.to_lowercase() == process_name).unwrap().unwrap(); let em_addr = p_handle.read_u32(0x01AF014C).unwrap() as u64; let num_p1 = p_handle.read_u8(em_addr + 6).unwrap(); let num_p2 = p_handle.read_u8(em_addr + 7).unwrap(); let num_p3 = p_handle.read_u8(em_addr + 8).unwrap(); let num_en = p_handle.read_u8(em_addr + 9).unwrap(); let read_list = |addr, num| { let mut pieces = Vec::new(); let mut addr = p_handle.read_u32(addr).unwrap() as u64; for _ in 0..num { let major_id = p_handle.read_u8(addr).unwrap(); let minor_id = p_handle.read_u8(addr + 1).unwrap(); let x = p_handle.read_f32(addr + 4).unwrap(); let y = p_handle.read_f32(addr + 8).unwrap(); let z = p_handle.read_f32(addr + 12).unwrap(); pieces.push(Emerald { id: (major_id as u16) << 8 | minor_id as u16, position: Vector { x: x, y: y, z: z, } }); addr += 16; } pieces }; let p1_list = read_list(em_addr + 0x5C, num_p1); let p2_list = read_list(em_addr + 0x60, num_p2); let p3_list = read_list(em_addr + 0x64, num_p3); let en_list = read_list(em_addr + 0x68, num_en); let rng_state = p_handle.read_u32(0x05CE05BC).unwrap(); let mut r = Rng::new(0xDEAD0CAB); let mut calls = 0; while r.get_state() != rng_state { calls += 1; r.gen_val::<P::Consts>(); } StageSpec { slot1_pieces: p1_list, slot2_pieces: p2_list, slot3_pieces: p3_list, enemy_pieces: en_list, pre_calls: calls, } } pub fn from_path<P, A>(filename: A) -> StageSpec where P: Platform, A: AsRef<Path>, { let mut file = File::open(filename).unwrap(); file.seek(SeekFrom::Start(0x00C5D5A6)).unwrap(); let num_p1 = file.read_u8().unwrap(); let num_p2 = file.read_u8().unwrap(); let num_p3 = file.read_u8().unwrap(); let num_en = file.read_u8().unwrap(); file.seek(SeekFrom::Start(0x00C5D5FC)).unwrap(); let p1_addr = file.read_u32::<BE>().unwrap() ^ 0x80000000; let p2_addr = file.read_u32::<BE>().unwrap() ^ 0x80000000; let p3_addr = file.read_u32::<BE>().unwrap() ^ 0x80000000; let en_addr = file.read_u32::<BE>().unwrap() ^ 0x80000000; file.seek(SeekFrom::Start(0x003AD6A0)).unwrap(); let rng_state = file.read_u32::<BE>().unwrap(); let mut read_list = |addr, num| { let mut pieces = Vec::new(); file.seek(SeekFrom::Start(addr)).unwrap(); for _ in 0..num { let id = file.read_u16::<BE>().unwrap(); let _padding = file.read_u16::<BE>().unwrap(); let x = file.read_f32::<BE>().unwrap(); let y = file.read_f32::<BE>().unwrap(); let z = file.read_f32::<BE>().unwrap(); pieces.push(Emerald { id: id, position: Vector { x: x, y: y, z: z, } }); } pieces }; let p1_list = read_list(p1_addr as u64, num_p1); let p2_list = read_list(p2_addr as u64, num_p2); let p3_list = read_list(p3_addr as u64, num_p3); let en_list = read_list(en_addr as u64, num_en); let mut r = Rng::new(0xDEAD0CAB); let mut calls = 0; while r.get_state() != rng_state { calls += 1; r.gen_val::<P::Consts>(); } StageSpec { slot1_pieces: p1_list, slot2_pieces: p2_list, slot3_pieces: p3_list, enemy_pieces: en_list, pre_calls: calls, } } }
use std::fs::File; use std::io::{Read, Seek, SeekFrom}; use std::path::Path; use serde_derive::{Serialize, Deserialize}; #[cfg(windows)] use process_reader::ProcessHandle; use byteorder::{ReadBytesExt, BE}; use crate::vector::Vector; use crate::rng::Rng; use crate::Platform; #[derive(Clone, Copy, Debug, Serialize, Deserialize)] pub struct Emerald { pub id: u16, pub position: Vector, } impl Default for Emerald { fn default() -> Emerald { Emerald { id: 0xFF00, position: Vector::default(), } } } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct StageSpec { pub slot1_pieces: Vec<Emerald>, pub slot2_pieces: Vec<Emerald>, pub slot3_pieces: Vec<Emerald>, pub enemy_pieces: Vec<Emerald>, pub pre_calls: u32, } impl StageSpec { #[cfg(windows)] pub fn from_process<P>(process_name: &str) -> StageSpec where P: Platform, { let p_handle = ProcessHandle::from_name_filter(|s| s.to_lowercase() == process_name).unwrap().unwrap(); let em_addr = p_handle.read_u32(0x01AF014C).unwrap() as u64; let num_p1 = p_handle.read_u8(em_addr + 6).unwrap(); let num_p2 = p_handle.read_u8(em_addr + 7).unwrap(); let num_p3 = p_handle.read_u8(em_addr + 8).unwrap(); let num_en = p_handle.read_u8(em_addr + 9).unwrap(); let read_list = |addr, num| { let mut pieces = Vec::new(); let mut addr = p_handle.read_u32(addr).unwrap() as u64; for _ in 0..num { let major_id = p_handle.read_u8(addr).unwrap(); let minor_id = p_handle.read_u8(addr + 1).unwrap(); let x = p_handle.read_f32(addr + 4).unwrap(); let y = p_handle.read_f32(addr + 8).unwrap(); let z = p_handle.read_f32(addr + 12).unwrap(); pieces.push(Emerald { id: (major_id as u16) << 8 | minor_id as u16, position: Vector { x: x, y: y, z: z, } }); addr += 16; } pieces }; let p1_list = read_list(em_addr + 0x5C, num_p1); let p2_list = read_list(em_addr + 0x60, num_p2); let p3_list = read_list(em_addr + 0x64, num_p3); let en_list = read_list(em_addr + 0x68, num_en); let rng_state = p_handle.read_u32(0x05CE05BC).unwrap(); let mut r = Rng::new(0xDEAD0CAB); let mut calls = 0; while r.get_state() != rng_state { calls += 1; r.gen_val::<P::Consts>(); } StageSpec { slot1_pieces: p1_list, slot2_pieces: p2_list, slot3_pieces: p3_list, enemy_pieces: en_list, pre_calls: calls, } } pub fn from_path<P, A>(filename: A) -> StageSpec where P: Platform, A: AsRef<Path>, { let mut file = File::open(filename).unwrap(); file.seek(SeekFrom::Start(0x00C5D5A6)).unwrap(); let num_p1 = file.read_u8().unwrap(); let num_p2 = file.read_u8().unwrap(); let num_p3 = file.read_u8().unwrap(); let num_en = file.read_u8().unwrap(); file.seek(SeekFrom::Start(0x00C5D5FC)).unwrap(); let p1_addr = file.read_u32::<BE>().unwrap() ^ 0x80000000; let p2_addr = file.read_u32::<BE>().unwrap() ^ 0x80000000; let p3_addr = file.read_u32::<BE>().unwr
let mut pieces = Vec::new(); file.seek(SeekFrom::Start(addr)).unwrap(); for _ in 0..num { let id = file.read_u16::<BE>().unwrap(); let _padding = file.read_u16::<BE>().unwrap(); let x = file.read_f32::<BE>().unwrap(); let y = file.read_f32::<BE>().unwrap(); let z = file.read_f32::<BE>().unwrap(); pieces.push(Emerald { id: id, position: Vector { x: x, y: y, z: z, } }); } pieces }; let p1_list = read_list(p1_addr as u64, num_p1); let p2_list = read_list(p2_addr as u64, num_p2); let p3_list = read_list(p3_addr as u64, num_p3); let en_list = read_list(en_addr as u64, num_en); let mut r = Rng::new(0xDEAD0CAB); let mut calls = 0; while r.get_state() != rng_state { calls += 1; r.gen_val::<P::Consts>(); } StageSpec { slot1_pieces: p1_list, slot2_pieces: p2_list, slot3_pieces: p3_list, enemy_pieces: en_list, pre_calls: calls, } } }
ap() ^ 0x80000000; let en_addr = file.read_u32::<BE>().unwrap() ^ 0x80000000; file.seek(SeekFrom::Start(0x003AD6A0)).unwrap(); let rng_state = file.read_u32::<BE>().unwrap(); let mut read_list = |addr, num| {
random
[ { "content": "pub trait Platform {\n\n type SquareRoot: vector::Sqrt;\n\n type Consts: rng::RngConsts;\n\n}\n\n\n\npub struct Gc;\n\n\n\nimpl Platform for Gc {\n\n type SquareRoot = vector::GcFp;\n\n type Consts = rng::GcRng;\n\n}\n\n\n\npub struct Pc;\n\n\n\nimpl Platform for Pc {\n\n type Squar...
Rust
examples/circle_packing.rs
mitchmindtree/nannou_egui
d79939e01e6e170ad1933fc528d2bd36bb03fbe4
use nannou::{color::rgb_u32, rand::thread_rng}; use nannou::{prelude::*, rand::prelude::SliceRandom}; use nannou_egui::{self, egui, EguiBackend}; const WIDTH: f32 = 640.0; const HEIGHT: f32 = 360.0; pub fn main() { nannou::app(model) .update(update) .size(WIDTH as u32, HEIGHT as u32) .run(); } struct Circle { x: f32, y: f32, radius: f32, color: Hsv, } struct Settings { min_radius: f32, max_radius: f32, circle_count: usize, } struct Model { circles: Vec<Circle>, settings: Settings, egui_backend: EguiBackend, } impl Model { pub fn new(egui_backend: EguiBackend) -> Model { Model { circles: Vec::new(), egui_backend, settings: Settings { min_radius: 10.0, max_radius: 100.0, circle_count: 10, }, } } pub fn generate_circles(&mut self) { let colors = [ color_from_hex_rgb(0x264653), color_from_hex_rgb(0x2a9d8f), color_from_hex_rgb(0xe9c46a), color_from_hex_rgb(0xf4a261), color_from_hex_rgb(0xe76f51), ]; let mut circles = Vec::new(); let mut rng = thread_rng(); let mut loops = 0; loop { let x = random_range(-WIDTH / 2.0, WIDTH / 2.0); let y = random_range(-HEIGHT / 2.0, HEIGHT / 2.0); let radius = random_range(self.settings.min_radius, self.settings.max_radius); let color = *colors.choose(&mut rng).unwrap(); let mut circle = Circle { x, y, radius, color, }; loops += 1; if loops > 20000 { break; } if intersects(&circle, &circles) { continue; } let mut prev_radius = circle.radius; while !intersects(&circle, &circles) { prev_radius = circle.radius; circle.radius += 10.0; if circle.radius >= self.settings.max_radius { break; } } circle.radius = prev_radius; circles.push(circle); if circles.len() >= self.settings.circle_count { break; } } self.circles = circles; } } fn intersects(circle: &Circle, circles: &Vec<Circle>) -> bool { for other in circles.iter() { let dist: f32 = ((other.x - circle.x).pow(2) as f32 + (other.y - circle.y).pow(2) as f32).sqrt(); if dist < circle.radius + other.radius { return true; } } false } fn model(app: &App) -> Model { let window_id = app .new_window() .view(view) .msaa_samples(1) .raw_event(raw_window_event) .build() .unwrap(); let window = app.window(window_id).unwrap(); Model::new(EguiBackend::new(&window)) } fn update(_app: &App, model: &mut Model, _update: Update) { let ctx = model.egui_backend.begin_frame(); egui::Window::new("Workshop window") .default_pos(egui::pos2(0.0, 0.0)) .show(&ctx, |ui| { ui.add( egui::Slider::new(&mut model.settings.min_radius, 0.0..=20.0).text("min radius"), ); ui.add( egui::Slider::new(&mut model.settings.max_radius, 0.0..=200.0).text("max radius"), ); ui.add( egui::Slider::new(&mut model.settings.circle_count, 0..=2000).text("circle count"), ); if ui.button("Generate").clicked() { model.generate_circles(); } }); model.egui_backend.end_frame(); } fn raw_window_event(_app: &App, model: &mut Model, event: &nannou::winit::event::WindowEvent) { model.egui_backend.handle_event(event); } fn view(app: &App, model: &Model, frame: Frame) { let draw = app.draw(); draw.background().color(BLACK); for circle in model.circles.iter() { draw.ellipse() .x_y(circle.x, circle.y) .radius(circle.radius) .color(circle.color); } draw.to_frame(app, &frame).unwrap(); model.egui_backend.draw_ui_to_frame(&frame); } pub fn color_from_hex_rgb(color: u32) -> Hsv { let color = rgb_u32(color); rgba( color.red as f32 / 255.0, color.green as f32 / 255.0, color.blue as f32 / 255.0, 1.0, ) .into() }
use nannou::{color::rgb_u32, rand::thread_rng}; use nannou::{prelude::*, rand::prelude::SliceRandom}; use nannou_egui::{self, egui, EguiBackend}; const WIDTH: f32 = 640.0; const HEIGHT: f32 = 360.0; pub fn main() { nannou::app(model) .update(update) .size(WIDTH as u32, HEIGHT as u32) .run(); } struct Circle { x: f32, y: f32, radius: f32, color: Hsv, } struct Settings { min_radius: f32, max_radius: f32, circle_count: usize, } struct Model { circles: Vec<Circle>, settings: Settings, egui_backend: EguiBackend, } impl Model { pub fn new(egui_backend: EguiBackend) -> Model { Model { circles: Vec::new(), egui_backend, settings: Settings { min_radius: 10.0, max_radius: 100.0, circle_count: 10, }, } } pub fn generate_circles(&mut self) { let colors = [ color_from_hex_rgb(0x264653), color_from_hex_rgb(0x2a9d8f), color_from_hex_rgb(0xe9c46a), color_from_hex_rgb(0xf4a261), color_from_hex_rgb(0xe76f51), ]; let mut circles = Vec::new(); let mut rng = thread_rng(); let mut loops = 0; loop { let x = random_range(-WIDTH / 2.0, WIDTH / 2.0); let y = random_range(-HEIGHT / 2.0, HEIGHT / 2.0); let radius = random_range(self.settings.min_radius, self.settings.max_radius); let color = *colors.choose(&mut rng).unwrap(); let mut circle = Circle { x, y, radius, color, }; loops += 1; if loops > 20000 { break; } if intersects(&circle, &circles) { continue; } let mut prev_radius = circle.radius; while !intersects(&circle, &circles) { prev_radius = circle.radius; circle.radius += 10.0; if circle.radius >= self.settings.max_radius { break; } } circle.radius = prev_radius; circles.push(circle); if circles.len() >= self.settings.circle_count { break; } } self.circles = circles; } } fn intersects(circle: &Circle, circles: &Vec<Circle>) -> bool { for other in circles.iter() { let dist: f32 = ((other.x - circle.x).pow(2) as f32 + (other.y - circle.y).pow(2) as f32).sqrt(); if dist < circle.radius + other.radius { return true; } } false } fn model(app: &App) -> Model { let window_id = app .new_window() .view(view) .msaa_samples(1) .raw_event(raw_window_event) .build() .unwrap(); let window = app.window(window_id).unwrap(); Model::new(EguiBackend::new(&window)) } fn update(_app: &App, model: &mut Model, _update: Update) { let ctx = model.egui_backend.begin_frame(); egui::Window::new("Workshop window") .default_pos(egui::pos2(0.0, 0.0)) .show(&ctx, |ui| { ui.add( egui::Slider::new(&mut model.settings.min_radius, 0.0..=20.0).text("min radius"), ); ui.add( egui::Slider::new(&mut model.settings.max_radius, 0.0..=200.0).text("max radius"), ); ui.add( egui::Slider::new(&mut model.settings.circle_count, 0..=2000).text("circle count"), ); if ui.button("Generate").clicked() { model.generate_circles(); } }); model.egui_backend.end_frame(); } fn raw_window_event(_app: &App, model: &mut Model, event: &nannou::winit::event::WindowEvent) { model.egui_backend.handle_event(event); } fn view(app: &App, model: &Model, frame: Frame) { let draw = app.draw(); draw.background().color(BLACK); for circle in model.circles.iter() { draw.ellipse() .x_y(circle.x, circle.y) .radius(circle.radius) .color(circle.color); } draw.to_frame(app, &frame).unwrap(); model.egui_backend.draw_ui_to_frame(&frame); } pub fn color_from_hex_rgb(color: u32) -> Hsv { let color = rgb_u32(color);
.into() }
rgba( color.red as f32 / 255.0, color.green as f32 / 255.0, color.blue as f32 / 255.0, 1.0, )
call_expression
[ { "content": "pub fn edit_color(ui: &mut egui::Ui, color: &mut nannou::color::Hsv) {\n\n let mut egui_hsv = egui::color::Hsva::new(\n\n color.hue.to_positive_radians() as f32 / (std::f32::consts::PI * 2.0),\n\n color.saturation,\n\n color.value,\n\n 1.0,\n\n );\n\n\n\n if co...
Rust
src/devices/tools/banjo/src/fidl.rs
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
use { lazy_static::lazy_static, regex::Regex, serde::{Deserialize, Deserializer}, serde_derive::{Deserialize, Serialize}, std::collections::BTreeMap, }; lazy_static! { pub static ref IDENTIFIER_RE: Regex = Regex::new(r#"^[A-Za-z]([_A-Za-z0-9]*[A-Za-z0-9])?$"#).unwrap(); pub static ref COMPOUND_IDENTIFIER_RE: Regex = Regex::new(r#"([_A-Za-z][_A-Za-z0-9]*-)*[_A-Za-z][_A-Za-z0-9]*/[_A-Za-z][_A-Za-z0-9]*"#) .unwrap(); pub static ref LIBRARY_IDENTIFIER_RE: Regex = Regex::new(r#"^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)*$"#).unwrap(); pub static ref VERSION_RE: Regex = Regex::new(r#"^[0-9]+\.[0-9]+\.[0-9]+$"#).unwrap(); } #[derive(Clone, Debug, PartialEq, Eq, Default, Serialize, Deserialize)] #[serde(transparent)] pub struct Ordinal(#[serde(deserialize_with = "validate_ordinal")] pub u32); fn validate_ordinal<'de, D>(deserializer: D) -> Result<u32, D::Error> where D: Deserializer<'de>, { let ordinal = u32::deserialize(deserializer)?; if ordinal == 0 { return Err(serde::de::Error::custom("Ordinal must not be equal to 0")); } Ok(ordinal) } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[repr(transparent)] pub struct Count(pub u32); #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct Identifier(#[serde(deserialize_with = "validate_identifier")] pub String); fn validate_identifier<'de, D>(deserializer: D) -> Result<String, D::Error> where D: Deserializer<'de>, { let id = String::deserialize(deserializer)?; if !IDENTIFIER_RE.is_match(&id) { return Err(serde::de::Error::custom(format!("Invalid identifier: {}", id))); } Ok(id) } #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] #[serde(transparent)] pub struct CompoundIdentifier( #[serde(deserialize_with = "validate_compound_identifier")] pub String, ); fn validate_compound_identifier<'de, D>(deserializer: D) -> Result<String, D::Error> where D: Deserializer<'de>, { let id = String::deserialize(deserializer)?; if !COMPOUND_IDENTIFIER_RE.is_match(&id) { return Err(serde::de::Error::custom(format!("Invalid compound identifier: {}", id))); } Ok(id) } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct LibraryIdentifier(#[serde(deserialize_with = "validate_library_identifier")] pub String); fn validate_library_identifier<'de, D>(deserializer: D) -> Result<String, D::Error> where D: Deserializer<'de>, { let id = String::deserialize(deserializer)?; if !LIBRARY_IDENTIFIER_RE.is_match(&id) { return Err(serde::de::Error::custom(format!("Invalid library identifier: {}", id))); } Ok(id) } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct Version(#[serde(deserialize_with = "validate_version")] pub String); fn validate_version<'de, D>(deserializer: D) -> Result<String, D::Error> where D: Deserializer<'de>, { let version = String::deserialize(deserializer)?; if !VERSION_RE.is_match(&version) { return Err(serde::de::Error::custom(format!("Invalid version: {}", version))); } Ok(version) } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Declaration { Const, Enum, Interface, Struct, Table, Union, XUnion, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct DeclarationsMap(pub BTreeMap<CompoundIdentifier, Declaration>); #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Library { pub name: LibraryIdentifier, pub declarations: DeclarationsMap, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Location { pub filename: String, pub line: u32, pub column: u32, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum HandleSubtype { Handle, Process, Thread, Vmo, Channel, Event, Port, Interrupt, Debuglog, Socket, Resource, Eventpair, Job, Vmar, Fifo, Guest, Timer, Bti, Profile, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum IntegerType { Int8, Int16, Int32, Int64, Uint8, Uint16, Uint32, Uint64, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum PrimitiveSubtype { Bool, Float32, Float64, Int8, Int16, Int32, Int64, Uint8, Uint16, Uint32, Uint64, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "lowercase")] pub enum Type { Array { element_type: Box<Type>, element_count: Count, }, Vector { element_type: Box<Type>, maybe_element_count: Option<Count>, nullable: bool, }, #[serde(rename = "string")] Str { maybe_element_count: Option<Count>, nullable: bool, }, Handle { subtype: HandleSubtype, nullable: bool, }, Request { subtype: CompoundIdentifier, nullable: bool, }, Primitive { subtype: PrimitiveSubtype, }, Identifier { identifier: CompoundIdentifier, nullable: bool, }, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "lowercase")] pub enum Literal { #[serde(rename = "string")] Str { value: String, }, Numeric { value: String, }, True, False, #[serde(rename = "default")] _Default, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "lowercase")] pub enum Constant { Identifier { identifier: CompoundIdentifier }, Literal { literal: Literal }, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Const { pub name: CompoundIdentifier, pub location: Option<Location>, #[serde(rename = "type")] pub _type: Type, pub value: Constant, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct EnumMember { pub name: Identifier, pub location: Option<Location>, pub maybe_attributes: Option<Vec<Attribute>>, pub value: Constant, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Enum { pub maybe_attributes: Option<Vec<Attribute>>, pub name: CompoundIdentifier, pub location: Option<Location>, #[serde(rename = "type")] pub _type: IntegerType, pub members: Vec<EnumMember>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Attribute { pub name: String, pub value: String, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct MethodParameter { #[serde(rename = "type")] pub _type: Type, pub name: Identifier, pub location: Option<Location>, pub size: Count, pub max_out_of_line: Count, pub alignment: Count, pub offset: Count, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Method { pub maybe_attributes: Option<Vec<Attribute>>, pub ordinal: Ordinal, pub generated_ordinal: Ordinal, pub name: Identifier, pub location: Option<Location>, pub has_request: bool, pub maybe_request: Option<Vec<MethodParameter>>, pub maybe_request_size: Option<Count>, pub maybe_request_alignment: Option<Count>, pub has_response: bool, pub maybe_response: Option<Vec<MethodParameter>>, pub maybe_response_size: Option<Count>, pub maybe_response_alignment: Option<Count>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Interface { pub maybe_attributes: Option<Vec<Attribute>>, pub name: CompoundIdentifier, pub location: Option<Location>, pub methods: Vec<Method>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct StructMember { #[serde(rename = "type")] pub _type: Type, pub name: Identifier, pub location: Option<Location>, pub size: Count, pub max_out_of_line: Count, pub alignment: Count, pub offset: Count, pub maybe_attributes: Option<Vec<Attribute>>, pub maybe_default_value: Option<Constant>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Struct { pub max_handles: Option<Count>, pub maybe_attributes: Option<Vec<Attribute>>, pub name: CompoundIdentifier, pub location: Option<Location>, pub anonymous: Option<bool>, pub members: Vec<StructMember>, pub size: Count, pub max_out_of_line: Count, } #[derive(Clone, Debug, PartialEq, Eq, Default, Serialize, Deserialize)] pub struct TableMember { pub ordinal: Ordinal, pub reserved: bool, #[serde(rename = "type")] pub _type: Option<Type>, pub name: Option<Identifier>, pub location: Option<Location>, pub size: Option<Count>, pub max_out_of_line: Option<Count>, pub alignment: Option<Count>, pub offset: Option<Count>, pub maybe_default_value: Option<Constant>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Table { pub max_handles: Option<Count>, pub maybe_attributes: Option<Vec<Attribute>>, pub name: CompoundIdentifier, pub location: Option<Location>, pub members: Vec<TableMember>, pub size: Count, pub max_out_of_line: Count, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct UnionMember { #[serde(rename = "type")] pub _type: Type, pub name: Identifier, pub location: Option<Location>, pub size: Count, pub max_out_of_line: Count, pub alignment: Count, pub offset: Count, pub maybe_attributes: Option<Vec<Attribute>>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Union { pub max_handles: Option<Count>, pub maybe_attributes: Option<Vec<Attribute>>, pub name: CompoundIdentifier, pub location: Option<Location>, pub members: Vec<UnionMember>, pub size: Count, pub max_out_of_line: Count, pub alignment: Count, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct XUnionMember { pub ordinal: Ordinal, #[serde(rename = "type")] pub _type: Type, pub name: Identifier, pub location: Option<Location>, pub size: Count, pub max_out_of_line: Count, pub alignment: Count, pub offset: Count, pub maybe_attributes: Option<Vec<Attribute>>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct XUnion { pub max_handles: Option<Count>, pub maybe_attributes: Option<Vec<Attribute>>, pub name: CompoundIdentifier, pub location: Option<Location>, pub members: Vec<XUnionMember>, pub size: Count, pub max_out_of_line: Count, pub alignment: Count, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Ir { pub version: Version, pub name: LibraryIdentifier, pub library_dependencies: Vec<Library>, pub const_declarations: Vec<Const>, pub enum_declarations: Vec<Enum>, pub interface_declarations: Vec<Interface>, pub struct_declarations: Vec<Struct>, pub table_declarations: Vec<Table>, pub union_declarations: Vec<Union>, pub xunion_declarations: Vec<XUnion>, pub declaration_order: Vec<CompoundIdentifier>, pub declarations: DeclarationsMap, }
use { lazy_static::lazy_static, regex::Regex, serde::{Deserialize, Deserializer}, serde_derive::{Deserialize, Serialize}, std::collections::BTreeMap, }; lazy_static! { pub static ref IDENTIFIER_RE: Regex = Regex::new(r#"^[A-Za-z]([_A-Za-z0-9]*[A-Za-z0-9])?$"#).unwrap(); pub static ref COMPOUND_IDENTIFIER_RE: Regex = Regex::new(r#"([_A-Za-z][_A-Za-z0-9]*-)*[_A-Za-z][_A-Za-z0-9]*/[_A-Za-z][_A-Za-z0-9]*"#) .unwrap(); pub static ref LIBRARY_IDENTIFIER_RE: Regex = Regex::new(r#"^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)*$"#).unwrap(); pub static ref VERSION_RE: Regex = Regex::new(r#"^[0-9]+\.[0-9]+\.[0-9]+$"#).unwrap(); } #[derive(Clone, Debug, PartialEq, Eq, Default, Serialize, Deserialize)] #[serde(transparent)] pub struct Ordinal(#[serde(deserialize_with = "validate_ordinal")] pub u32); fn validate_ordinal<'de, D>(deserializer: D) -> Result<u32, D::Error> where D: Deserializer<'de>, { let ordinal = u32::deserialize(deserializer)?; if ordinal == 0 { return Err(serde::de::Error::custom("Ordinal must not be equal to 0")); } Ok(ordinal) } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[repr(transparent)] pub struct Count(pub u32); #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct Identifier(#[serde(deserialize_with = "validate_identifier")] pub String); fn validate_identifier<'de, D>(deserializer: D) -> Result<String, D::Error> where D: Deserializer<'de>, { let id = String::deserialize(deserializer)?; if !IDENTIFIER_RE.is_match(&id) { return Err(serde::de::Error::custom(format!("Invalid identifier: {}", id))); } Ok(id) } #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] #[serde(transparent)] pub struct CompoundIdentifier( #[serde(deserialize_with = "validate_compound_identifier")] pub String, ); fn validate_compound_identifier<'de, D>(deserializer: D) -> Result<String, D::Error> where D: Deserializer<'de>, { let id = String::deserialize(deserializer)?; if !COMPOUND_IDENTIFIER_RE.is_match(&id) { return Err(serde::de::Error::custom(format!("Invalid compound identifier: {}", id))); } Ok(id) } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct LibraryIdentifier(#[serde(deserialize_with = "validate_library_identifier")] pub String);
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct Version(#[serde(deserialize_with = "validate_version")] pub String); fn validate_version<'de, D>(deserializer: D) -> Result<String, D::Error> where D: Deserializer<'de>, { let version = String::deserialize(deserializer)?; if !VERSION_RE.is_match(&version) { return Err(serde::de::Error::custom(format!("Invalid version: {}", version))); } Ok(version) } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Declaration { Const, Enum, Interface, Struct, Table, Union, XUnion, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct DeclarationsMap(pub BTreeMap<CompoundIdentifier, Declaration>); #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Library { pub name: LibraryIdentifier, pub declarations: DeclarationsMap, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Location { pub filename: String, pub line: u32, pub column: u32, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum HandleSubtype { Handle, Process, Thread, Vmo, Channel, Event, Port, Interrupt, Debuglog, Socket, Resource, Eventpair, Job, Vmar, Fifo, Guest, Timer, Bti, Profile, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum IntegerType { Int8, Int16, Int32, Int64, Uint8, Uint16, Uint32, Uint64, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum PrimitiveSubtype { Bool, Float32, Float64, Int8, Int16, Int32, Int64, Uint8, Uint16, Uint32, Uint64, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "lowercase")] pub enum Type { Array { element_type: Box<Type>, element_count: Count, }, Vector { element_type: Box<Type>, maybe_element_count: Option<Count>, nullable: bool, }, #[serde(rename = "string")] Str { maybe_element_count: Option<Count>, nullable: bool, }, Handle { subtype: HandleSubtype, nullable: bool, }, Request { subtype: CompoundIdentifier, nullable: bool, }, Primitive { subtype: PrimitiveSubtype, }, Identifier { identifier: CompoundIdentifier, nullable: bool, }, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "lowercase")] pub enum Literal { #[serde(rename = "string")] Str { value: String, }, Numeric { value: String, }, True, False, #[serde(rename = "default")] _Default, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "lowercase")] pub enum Constant { Identifier { identifier: CompoundIdentifier }, Literal { literal: Literal }, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Const { pub name: CompoundIdentifier, pub location: Option<Location>, #[serde(rename = "type")] pub _type: Type, pub value: Constant, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct EnumMember { pub name: Identifier, pub location: Option<Location>, pub maybe_attributes: Option<Vec<Attribute>>, pub value: Constant, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Enum { pub maybe_attributes: Option<Vec<Attribute>>, pub name: CompoundIdentifier, pub location: Option<Location>, #[serde(rename = "type")] pub _type: IntegerType, pub members: Vec<EnumMember>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Attribute { pub name: String, pub value: String, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct MethodParameter { #[serde(rename = "type")] pub _type: Type, pub name: Identifier, pub location: Option<Location>, pub size: Count, pub max_out_of_line: Count, pub alignment: Count, pub offset: Count, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Method { pub maybe_attributes: Option<Vec<Attribute>>, pub ordinal: Ordinal, pub generated_ordinal: Ordinal, pub name: Identifier, pub location: Option<Location>, pub has_request: bool, pub maybe_request: Option<Vec<MethodParameter>>, pub maybe_request_size: Option<Count>, pub maybe_request_alignment: Option<Count>, pub has_response: bool, pub maybe_response: Option<Vec<MethodParameter>>, pub maybe_response_size: Option<Count>, pub maybe_response_alignment: Option<Count>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Interface { pub maybe_attributes: Option<Vec<Attribute>>, pub name: CompoundIdentifier, pub location: Option<Location>, pub methods: Vec<Method>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct StructMember { #[serde(rename = "type")] pub _type: Type, pub name: Identifier, pub location: Option<Location>, pub size: Count, pub max_out_of_line: Count, pub alignment: Count, pub offset: Count, pub maybe_attributes: Option<Vec<Attribute>>, pub maybe_default_value: Option<Constant>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Struct { pub max_handles: Option<Count>, pub maybe_attributes: Option<Vec<Attribute>>, pub name: CompoundIdentifier, pub location: Option<Location>, pub anonymous: Option<bool>, pub members: Vec<StructMember>, pub size: Count, pub max_out_of_line: Count, } #[derive(Clone, Debug, PartialEq, Eq, Default, Serialize, Deserialize)] pub struct TableMember { pub ordinal: Ordinal, pub reserved: bool, #[serde(rename = "type")] pub _type: Option<Type>, pub name: Option<Identifier>, pub location: Option<Location>, pub size: Option<Count>, pub max_out_of_line: Option<Count>, pub alignment: Option<Count>, pub offset: Option<Count>, pub maybe_default_value: Option<Constant>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Table { pub max_handles: Option<Count>, pub maybe_attributes: Option<Vec<Attribute>>, pub name: CompoundIdentifier, pub location: Option<Location>, pub members: Vec<TableMember>, pub size: Count, pub max_out_of_line: Count, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct UnionMember { #[serde(rename = "type")] pub _type: Type, pub name: Identifier, pub location: Option<Location>, pub size: Count, pub max_out_of_line: Count, pub alignment: Count, pub offset: Count, pub maybe_attributes: Option<Vec<Attribute>>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Union { pub max_handles: Option<Count>, pub maybe_attributes: Option<Vec<Attribute>>, pub name: CompoundIdentifier, pub location: Option<Location>, pub members: Vec<UnionMember>, pub size: Count, pub max_out_of_line: Count, pub alignment: Count, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct XUnionMember { pub ordinal: Ordinal, #[serde(rename = "type")] pub _type: Type, pub name: Identifier, pub location: Option<Location>, pub size: Count, pub max_out_of_line: Count, pub alignment: Count, pub offset: Count, pub maybe_attributes: Option<Vec<Attribute>>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct XUnion { pub max_handles: Option<Count>, pub maybe_attributes: Option<Vec<Attribute>>, pub name: CompoundIdentifier, pub location: Option<Location>, pub members: Vec<XUnionMember>, pub size: Count, pub max_out_of_line: Count, pub alignment: Count, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Ir { pub version: Version, pub name: LibraryIdentifier, pub library_dependencies: Vec<Library>, pub const_declarations: Vec<Const>, pub enum_declarations: Vec<Enum>, pub interface_declarations: Vec<Interface>, pub struct_declarations: Vec<Struct>, pub table_declarations: Vec<Table>, pub union_declarations: Vec<Union>, pub xunion_declarations: Vec<XUnion>, pub declaration_order: Vec<CompoundIdentifier>, pub declarations: DeclarationsMap, }
fn validate_library_identifier<'de, D>(deserializer: D) -> Result<String, D::Error> where D: Deserializer<'de>, { let id = String::deserialize(deserializer)?; if !LIBRARY_IDENTIFIER_RE.is_match(&id) { return Err(serde::de::Error::custom(format!("Invalid library identifier: {}", id))); } Ok(id) }
function_block-full_function
[]
Rust
src/main.rs
svenstaro/ggj2017
9d2cc2d01e33621096ac6aba20aa2889e4960856
pub mod utils; pub mod block; extern crate nalgebra as na; extern crate ncollide; extern crate nphysics2d; extern crate ggez; extern crate rand; use ggez::conf; use ggez::game::{Game, GameState}; use ggez::{GameResult, Context}; use ggez::graphics; use ggez::timer; use std::time::Duration; use rand::Rand; use std::collections::HashMap; use na::Vector2; use ncollide::shape::{Plane, Cuboid}; use nphysics2d::world::World; use nphysics2d::object::RigidBody; use ggez::event::*; use block::Block; use utils::draw_rectangle; struct MainState { text: graphics::Text, physics_world: World<f32>, blocks: Vec<Block>, player: Block, key_pressed: HashMap<Keycode, bool>, } impl GameState for MainState { fn load(ctx: &mut Context) -> GameResult<MainState> { let font = graphics::Font::new(ctx, "DejaVuSerif.ttf", 48).unwrap(); let text = graphics::Text::new(ctx, "Hello world!", &font).unwrap(); let mut world = World::new(); let explane = Block::new(RigidBody::new_dynamic(Cuboid::new(Vector2::new(100.0, 100.0)), 1.0, 0.3, 0.6), &mut world); let mut s = MainState { text: text, physics_world: world, blocks: Vec::new(), player: explane, key_pressed: HashMap::new(), }; s.physics_world.set_gravity(Vector2::new(0.0, 9.81)); let static_block = Block::new(RigidBody::new_dynamic(Cuboid::new(Vector2::new(2000.0, 10.0)), 1.0, 0.3, 0.6), &mut s.physics_world); static_block.body.borrow_mut().append_translation(&Vector2::new(0.0, 400.0)); s.blocks.push(static_block); s.player.body.borrow_mut().append_translation(&Vector2::new(400.0, 100.0)); Ok(s) } fn update(&mut self, _ctx: &mut Context, dt: Duration) -> GameResult<()> { self.physics_world.step(timer::duration_to_f64(dt) as f32); for (key, _) in self.key_pressed.iter() { match key { &Keycode::Right => { println!("right"); self.player.body.borrow_mut().apply_central_impulse(Vector2::new(2000.0, 0.0)); } &Keycode::Left => { println!("left"); self.player.body.borrow_mut().apply_central_impulse(Vector2::new(-2000.0, 0.0)); } &Keycode::Up => { println!("up"); self.player.body.borrow_mut().apply_central_impulse(Vector2::new(0.0, -2000.0)); } _ => (), } } Ok(()) } fn draw(&mut self, ctx: &mut Context) -> GameResult<()> { let mut rng = rand::thread_rng(); ctx.renderer.clear(); graphics::draw(ctx, &mut self.text, None, None)?; for block in &self.blocks { graphics::set_color(ctx, graphics::Color::rand(&mut rng)); draw_rectangle(ctx, block); } graphics::set_color(ctx, graphics::Color::RGB(0, 255, 0)); draw_rectangle(ctx, &self.player); graphics::set_color(ctx, graphics::Color::RGB(0, 0, 0)); ctx.renderer.present(); timer::sleep_until_next_frame(ctx, 60); Ok(()) } fn key_down_event(&mut self, _keycode: Keycode, _keymod: Mod, _repeat: bool) { if !_repeat { self.key_pressed.insert(_keycode, true); } } fn key_up_event(&mut self, _keycode: Keycode, _keymod: Mod, _repeat: bool) { if !_repeat { self.key_pressed.remove(&_keycode); } } } pub fn main() { let mut c = conf::Conf::new(); c.window_title = "ExPlane".to_string(); c.window_width = 1280; c.window_height = 720; let mut game: Game<MainState> = Game::new("helloworld", c).unwrap(); if let Err(e) = game.run() { println!("Error encountered: {}", e); } else { println!("Game exited cleanly."); } }
pub mod utils; pub mod block; extern crate nalgebra as na; extern crate ncollide; extern crate nphysics2d; extern crate ggez; extern crate rand; use ggez::conf; use ggez::game::{Game, GameState}; use ggez::{GameResult, Context}; use ggez::graphics; use ggez::timer; use std::time::Duration; use rand::Rand; use std::collections::HashMap; use na::Vector2; use ncollide::shape::{Plane, Cuboid}; use nphysics2d::world::World; use nphysics2d::object::RigidBody; use ggez::event::*; use block::Block; use utils::draw_rectangle; struct MainState { text: graphics::Text, physics_world: World<f32>, blocks: Vec<Block>, player: Block, key_pressed: HashMap<Keycode, bool>, } impl GameState for MainState { fn load(ctx: &mut Context) -> GameResult<MainState> { let font = graphics::Font::new(ctx, "DejaVuSerif.ttf", 48).unwrap(); let text = graphics::Text::new(ctx, "Hello world!", &font).unwrap(); let mut world = World::new(); let explane = Block::new(RigidBody::new_dynamic(Cuboid::new(Vector2::new(100.0, 100.0)), 1.0, 0.3, 0.6), &mut world); let mut s = MainState { text: text, physics_world: world, blocks: Vec::new(), player: explane, key_pressed: HashMap::new(), }; s.physics_world.set_gravity(Vector2::new(0.0, 9.81)); let static_block = Block::new(RigidBody::new_dynamic(Cuboid::new(Vector2::new(2000.0, 10.0)), 1.0, 0.3, 0.6), &mut s.physics_world); static_block.body.borrow_mut().append_translation(&Vector2::new(0.0, 400.0)); s.blocks.push(static_block); s.player.body.borrow_mut().append_translation(&Vector2::new(400.0, 100.0)); Ok(s) } fn update(&mut self, _ctx: &mut Context, dt: Duration) -> GameResult<()> { self.physics_world.step(timer::duration_to_f64(dt) as f32); for (key, _) in self.key_pressed.iter() { match key { &Keycode::Right => { println!("right"); self.player.body.borrow_mut().apply_central_impulse(Vector2::new(2000.0, 0.0)); } &Keycode::Left => { println!("left"); self.player.body.borrow_mut().apply_central_impulse(Vector2::new(-2000.0, 0.0)); } &Keycode::Up => { println!("up"); self.player.body.borrow_mut().apply_central_impulse(Vector2::new(0.0, -2000.0)); } _ => (), } } Ok(()) } fn draw(&mut self, ctx: &mut Context) -> GameResult<()> { let mut rng = rand::thread_rng(); ctx.renderer.clear(); graphics::draw(ctx, &mut self.text, None, None)?; for block in &self.blocks { graphics::set_color(ctx, graphics::Color::rand(&mut rng)); draw_rectangle(ctx, block); } graphics::set_color(ctx, graphics::Color::RGB(0, 255, 0)); draw_rectangle(
fn key_down_event(&mut self, _keycode: Keycode, _keymod: Mod, _repeat: bool) { if !_repeat { self.key_pressed.insert(_keycode, true); } } fn key_up_event(&mut self, _keycode: Keycode, _keymod: Mod, _repeat: bool) { if !_repeat { self.key_pressed.remove(&_keycode); } } } pub fn main() { let mut c = conf::Conf::new(); c.window_title = "ExPlane".to_string(); c.window_width = 1280; c.window_height = 720; let mut game: Game<MainState> = Game::new("helloworld", c).unwrap(); if let Err(e) = game.run() { println!("Error encountered: {}", e); } else { println!("Game exited cleanly."); } }
ctx, &self.player); graphics::set_color(ctx, graphics::Color::RGB(0, 0, 0)); ctx.renderer.present(); timer::sleep_until_next_frame(ctx, 60); Ok(()) }
function_block-function_prefixed
[ { "content": "pub fn draw_rectangle(ctx: &mut Context, block: &Block) {\n\n let body = block.body.borrow();\n\n\n\n if body.shape().is_shape::<Cuboid<Vector2<f32>>>() {\n\n let shape: &Cuboid<Vector2<f32>> = body.shape().as_shape().unwrap();\n\n let extents = shape.half_extents();\n\n ...
Rust
src/drv.rs
kaivol/smartoris-i2c
ce0526e04c95712b9b9c64ca5d6e6598ce65f530
use crate::{ diverged::{DmaChDiverged, I2CDiverged}, I2CMaster, }; use drone_cortexm::{fib, reg::prelude::*, thr::prelude::*}; use drone_stm32_map::periph::{ dma::ch::{traits::*, DmaChMap, DmaChPeriph}, i2c::{traits::*, I2CMap, I2CPeriph}, }; use futures::prelude::*; pub struct I2CSetup< I2C: I2CMap, I2CEv: IntToken, I2CEr: IntToken, DmaTx: DmaChMap, DmaTxInt: IntToken, DmaRx: DmaChMap, DmaRxInt: IntToken, > { pub i2c: I2CPeriph<I2C>, pub i2c_ev: I2CEv, pub i2c_er: I2CEr, pub i2c_freq: u32, pub i2c_presc: u32, pub i2c_trise: u32, pub i2c_mode: I2CMode, pub dma_tx: DmaChPeriph<DmaTx>, pub dma_tx_int: DmaTxInt, pub dma_tx_ch: u32, pub dma_tx_pl: u32, pub dma_rx: DmaChPeriph<DmaRx>, pub dma_rx_int: DmaRxInt, pub dma_rx_ch: u32, pub dma_rx_pl: u32, } #[derive(Clone, Copy)] pub enum I2CMode { Sm1, Fm2, Fm169, } pub struct I2CDrv< I2C: I2CMap, I2CEv: IntToken, I2CEr: IntToken, DmaTx: DmaChMap, DmaTxInt: IntToken, DmaRx: DmaChMap, DmaRxInt: IntToken, > { i2c: I2CDiverged<I2C>, i2c_ev: I2CEv, i2c_er: I2CEr, dma_tx: DmaChDiverged<DmaTx>, dma_tx_int: DmaTxInt, dma_rx: DmaChDiverged<DmaRx>, dma_rx_int: DmaRxInt, } impl< I2C: I2CMap, I2CEv: IntToken, I2CEr: IntToken, DmaTx: DmaChMap, DmaTxInt: IntToken, DmaRx: DmaChMap, DmaRxInt: IntToken, > I2CDrv<I2C, I2CEv, I2CEr, DmaTx, DmaTxInt, DmaRx, DmaRxInt> { #[must_use] pub fn init(setup: I2CSetup<I2C, I2CEv, I2CEr, DmaTx, DmaTxInt, DmaRx, DmaRxInt>) -> Self { let I2CSetup { i2c, i2c_ev, i2c_er, i2c_freq, i2c_presc, i2c_trise, i2c_mode, dma_tx, dma_tx_int, dma_tx_ch, dma_tx_pl, dma_rx, dma_rx_int, dma_rx_ch, dma_rx_pl, } = setup; let mut drv = Self { i2c: i2c.into(), i2c_ev, i2c_er, dma_tx: dma_tx.into(), dma_tx_int, dma_rx: dma_rx.into(), dma_rx_int, }; drv.init_i2c(i2c_freq, i2c_presc, i2c_trise, i2c_mode); drv.init_dma_tx(dma_tx_ch, dma_tx_pl); drv.init_dma_rx(dma_rx_ch, dma_rx_pl); drv } #[inline] pub fn master( &mut self, ) -> I2CMaster<'_, I2C, I2CEv, I2CEr, DmaTx, DmaTxInt, DmaRx, DmaRxInt> { while self.i2c.i2c_cr1.stop().read_bit() {} I2CMaster::new(self/*, buf*/) } pub(crate) unsafe fn write(&mut self, addr: u8, buf_tx: &[u8]) -> impl Future<Output = ()> { self.dma_tx(buf_tx); self.start(addr << 1, false) } pub(crate) unsafe fn read(&mut self, addr: u8, buf_rx: &mut [u8]) -> impl Future<Output = ()> { let dma_rx = self.dma_rx(buf_rx); self.start(addr << 1 | 1, buf_rx.len() > 1).then(|()| dma_rx) } pub(crate) fn stop(&mut self) { self.i2c.i2c_cr1.stop().set_bit(); } unsafe fn dma_tx(&mut self, buf_tx: &[u8]) { self.dma_tx.dma_cm0ar.store_reg(|r, v| { r.m0a().write(v, buf_tx.as_ptr() as u32); }); self.dma_tx.dma_cndtr.store_reg(|r, v| { r.ndt().write(v, buf_tx.len() as u32); }); self.dma_tx.dma_ifcr_ctcif.set_bit(); self.dma_tx.dma_ccr.modify_reg(|r, v| r.en().set(v)); } unsafe fn dma_rx(&mut self, buf_rx: &mut [u8]) -> impl Future<Output = ()> { let dma_ifcr_ctcif = self.dma_rx.dma_ifcr_ctcif; let dma_isr_dmeif = self.dma_rx.dma_isr_dmeif; let dma_isr_feif = self.dma_rx.dma_isr_feif; let dma_isr_tcif = self.dma_rx.dma_isr_tcif; let dma_isr_teif = self.dma_rx.dma_isr_teif; let future = self.dma_rx_int.add_future(fib::new_fn(move || { let val = dma_isr_tcif.load_val(); handle_dma_err::<DmaRx>(&val, dma_isr_dmeif, dma_isr_feif, dma_isr_teif); if dma_isr_tcif.read(&val) { dma_ifcr_ctcif.set_bit(); fib::Complete(()) } else { fib::Yielded(()) } })); self.dma_rx.dma_cm0ar.store_reg(|r, v| { r.m0a().write(v, buf_rx.as_mut_ptr() as u32); }); self.dma_rx.dma_cndtr.store_reg(|r, v| { r.ndt().write(v, buf_rx.len() as u32); }); self.dma_rx.dma_ccr.modify_reg(|r, v| r.en().set(v)); future } fn start(&mut self, addr: u8, ack: bool) -> impl Future<Output = ()> { let i2c_cr1 = self.i2c.i2c_cr1; let i2c_cr2 = self.i2c.i2c_cr2; let i2c_sr1 = self.i2c.i2c_sr1; let i2c_sr2 = self.i2c.i2c_sr2; let i2c_dr = self.i2c.i2c_dr; let set_start = move || { i2c_cr1.modify_reg(|r, v| { if ack { r.ack().set(v); } else { r.ack().clear(v); } r.start().set(v); }); }; let repeated = self.i2c.i2c_sr2.msl().read_bit(); let future = self.i2c_ev.add_future(fib::new_fn(move || { let sr1_val = i2c_sr1.load_val(); if i2c_sr1.sb().read(&sr1_val) { i2c_dr.store_reg(|r, v| r.dr().write(v, u32::from(addr))); fib::Yielded(()) } else if i2c_sr1.addr().read(&sr1_val) { let sr2_val = i2c_sr2.load_val(); if i2c_sr2.tra().read(&sr2_val) { fib::Yielded(()) } else { fib::Complete(()) } } else if i2c_sr1.btf().read(&sr1_val) { if repeated { set_start(); fib::Yielded(()) } else { i2c_cr2.itevten().clear_bit(); fib::Complete(()) } } else { fib::Yielded(()) } })); self.i2c.i2c_cr2.itevten().set_bit(); if !repeated { set_start(); } future } fn init_i2c(&mut self, i2c_freq: u32, i2c_presc: u32, i2c_trise: u32, i2c_mode: I2CMode) { self.i2c.rcc_busenr_i2cen.set_bit(); self.i2c.i2c_cr2.store_reg(|r, v| { r.last().set(v); r.dmaen().set(v); r.iterren().set(v); r.freq().write(v, i2c_freq); }); self.i2c.i2c_ccr.store_reg(|r, v| { match i2c_mode { I2CMode::Sm1 => { r.f_s().clear(v); } I2CMode::Fm2 => { r.f_s().set(v); r.duty().clear(v); } I2CMode::Fm169 => { r.f_s().set(v); r.duty().set(v); } } r.ccr().write(v, i2c_presc); }); self.i2c.i2c_trise.store_reg(|r, v| { r.trise().write(v, i2c_trise); }); self.i2c.i2c_cr1.store_reg(|r, v| r.pe().set(v)); let i2c_sr1 = self.i2c.i2c_sr1; self.i2c_er.add_fn(move || { let val = i2c_sr1.load_val(); handle_i2c_err::<I2C>(&val, i2c_sr1); fib::Yielded::<(), !>(()) }); } fn init_dma_tx(&mut self, channel: u32, priority: u32) { let address = self.i2c.i2c_dr.as_mut_ptr(); self.dma_tx.dma_cpar.store_reg(|r, v| { r.pa().write(v, address as u32); }); self.dma_tx.dma_ccr.store_reg(|r, v| { r.chsel().write(v, channel); r.pl().write(v, priority); r.msize().write(v, 0b00); r.psize().write(v, 0b00); r.minc().set(v); r.pinc().clear(v); r.dir().write(v, 0b01); r.tcie().clear(v); r.teie().set(v); }); let dma_isr_dmeif = self.dma_tx.dma_isr_dmeif; let dma_isr_feif = self.dma_tx.dma_isr_feif; let dma_isr_teif = self.dma_tx.dma_isr_teif; self.dma_tx_int.add_fn(move || { let val = dma_isr_teif.load_val(); handle_dma_err::<DmaTx>(&val, dma_isr_dmeif, dma_isr_feif, dma_isr_teif); fib::Yielded::<(), !>(()) }); } fn init_dma_rx(&mut self, channel: u32, priority: u32) { let address = self.i2c.i2c_dr.as_ptr(); self.dma_rx.dma_cpar.store_reg(|r, v| { r.pa().write(v, address as u32); }); self.dma_rx.dma_ccr.store_reg(|r, v| { r.chsel().write(v, channel); r.pl().write(v, priority); r.msize().write(v, 0b00); r.psize().write(v, 0b00); r.minc().set(v); r.pinc().clear(v); r.dir().write(v, 0b00); r.tcie().set(v); r.teie().set(v); }); } } fn handle_dma_err<T: DmaChMap>( val: &T::DmaIsrVal, dma_isr_dmeif: T::CDmaIsrDmeif, dma_isr_feif: T::CDmaIsrFeif, dma_isr_teif: T::CDmaIsrTeif, ) { if dma_isr_teif.read(&val) { panic!("Transfer error"); } if dma_isr_dmeif.read(&val) { panic!("Direct mode error"); } if dma_isr_feif.read(&val) { panic!("FIFO error"); } } fn handle_i2c_err<T: I2CMap>(val: &T::I2CSr1Val, i2c_sr1: T::CI2CSr1) { if i2c_sr1.berr().read(&val) { panic!("Misplaced Start or Stop condition"); } if i2c_sr1.arlo().read(&val) { panic!("Arbitration Lost detected"); } if i2c_sr1.af().read(&val) { panic!("Acknowledge failure"); } if i2c_sr1.ovr().read(&val) { panic!("Overrun or underrun"); } if i2c_sr1.timeout().read(&val) { panic!("SCL remained LOW for 25 ms"); } }
use crate::{ diverged::{DmaChDiverged, I2CDiverged}, I2CMaster, }; use drone_cortexm::{fib, reg::prelude::*, thr::prelude::*}; use drone_stm32_map::periph::{ dma::ch::{traits::*, DmaChMap, DmaChPeriph}, i2c::{traits::*, I2CMap, I2CPeriph}, }; use futures::prelude::*; pub struct I2CSetup< I2C: I2CMap, I2CEv: IntToken, I2CEr: IntToken, DmaTx: DmaChMap, DmaTxInt: IntToken, DmaRx: DmaChMap, DmaRxInt: IntToken, > { pub i2c: I2CPeriph<I2C>, pub i2c_ev: I2CEv, pub i2c_er: I2CEr, pub i2c_freq: u32, pub i2c_presc: u32, pub i2c_trise: u32, pub i2c_mode: I2CMode, pub dma_tx: DmaChPeriph<DmaTx>, pub dma_tx_int: DmaTxInt, pub dma_tx_ch: u32, pub dma_tx_pl: u32, pub dma_rx: DmaChPeriph<DmaRx>, pub dma_rx_int: DmaRxInt, pub dma_rx_ch: u32, pub dma_rx_pl: u32, } #[derive(Clone, Copy)] pub enum I2CMode { Sm1, Fm2, Fm169, } pub struct I2CDrv< I2C: I2CMap, I2CEv: IntToken, I2CEr: IntToken, DmaTx: DmaChMap, DmaTxInt: IntToken, DmaRx: DmaChMap, DmaRxInt: IntToken, > { i2c: I2CDiverged<I2C>, i2c_ev: I2CEv, i2c_er: I2CEr, dma_tx: DmaChDiverged<DmaTx>, dma_tx_int: DmaTxInt, dma_rx: DmaChDiverged<DmaRx>, dma_rx_int: DmaRxInt, } impl< I2C: I2CMap, I2CEv: IntToken, I2CEr: IntToken, DmaTx: DmaChMap, DmaTxInt: IntToken, DmaRx: DmaChMap, DmaRxInt: IntToken, > I2CDrv<I2C, I2CEv, I2CEr, DmaTx, DmaTxInt, DmaRx, DmaRxInt> { #[must_use] pub fn init(setup: I2CSetup<I2C, I2CEv, I2CEr, DmaTx, DmaTxInt, DmaRx, DmaRxInt>) -> Self { let I2CSetup { i2c, i2c_ev, i2c_er, i2c_freq, i2c_presc, i2c_trise, i2c_mode, dma_tx, dma_tx_int, dma_tx_ch, dma_tx_pl, dma_rx, dma_rx_int, dma_rx_ch, dma_rx_pl, } = setup; let mut drv = Self { i2c: i2c.into(), i2c_ev, i2c_er, dma_tx: dma_tx.into(), dma_tx_int, dma_rx: dma_rx.into(), dma_rx_int, }; drv.init_i2c(i2c_freq, i2c_presc, i2c_trise, i2c_mode); drv.init_dma_tx(dma_tx_ch, dma_tx_pl); drv.init_dma_rx(dma_rx_ch, dma_rx_pl); drv } #[inline] pub fn master( &mut self, ) -> I2CMaster<'_, I2C, I2CEv, I2CEr, DmaTx, DmaTxInt, DmaRx, DmaRxInt> { while self.i2c.i2c_cr1.stop().read_bit() {} I2CMaster::new(self/*, buf*/) } pub(crate) unsafe fn write(&mut self, addr: u8, buf_tx: &[u8]) -> impl Future<Output = ()> { self.dma_tx(buf_tx); self.start(addr << 1, false) } pub(crate) unsafe fn read(&mut self, addr: u8, buf_rx: &mut [u8]) -> impl Future<Output = ()> { let dma_rx = self.dma_rx(buf_rx); self.start(addr << 1 | 1, buf_rx.len() > 1).then(|()| dma_rx) } pub(crate) fn stop(&mut self) { self.i2c.i2c_cr1.stop().set_bit(); } unsafe fn dma_tx(&mut self, buf_tx: &[u8]) { self.dma_tx.dma_cm0ar.store_reg(|r, v| { r.m0a().write(v, buf_tx.as_ptr() as u32); }); self.dma_tx.dma_cndtr.store_reg(|r, v| { r.ndt().write(v, buf_tx.len() as u32); }); self.dma_tx.dma_ifcr_ctcif.set_bit(); self.dma_tx.dma_ccr.modify_reg(|r, v| r.en().set(v)); } unsafe fn dma_rx(&mut self, buf_rx: &mut [u8]) -> impl Future<Output = ()> { let dma_ifcr_ctcif = self.dma_rx.dma_ifcr_ctcif; let dma_isr_dmeif = self.dma_rx.dma_isr_dmeif; let dma_isr_feif = self.dma_rx.dma_isr_feif; let dma_isr_tcif = self.dma_rx.dma_isr_tcif; let dma_isr_teif = self.dma_rx.dma_isr_teif; let future = self.dma_rx_int.add_future(fib::new_fn(move || { let val = dma_isr_tcif.load_val(); handle_dma_err::<DmaRx>(&val, dma_isr_dmeif, dma_isr_feif, dma_isr_teif); if dma_isr_tcif.read(&val) { dma_ifcr_ctcif.set_bit(); fib::Complete(()) } else { fib::Yielded(()) } })); self.dma_rx.dma_cm0ar.store_reg(|r, v| {
} })); self.i2c.i2c_cr2.itevten().set_bit(); if !repeated { set_start(); } future } fn init_i2c(&mut self, i2c_freq: u32, i2c_presc: u32, i2c_trise: u32, i2c_mode: I2CMode) { self.i2c.rcc_busenr_i2cen.set_bit(); self.i2c.i2c_cr2.store_reg(|r, v| { r.last().set(v); r.dmaen().set(v); r.iterren().set(v); r.freq().write(v, i2c_freq); }); self.i2c.i2c_ccr.store_reg(|r, v| { match i2c_mode { I2CMode::Sm1 => { r.f_s().clear(v); } I2CMode::Fm2 => { r.f_s().set(v); r.duty().clear(v); } I2CMode::Fm169 => { r.f_s().set(v); r.duty().set(v); } } r.ccr().write(v, i2c_presc); }); self.i2c.i2c_trise.store_reg(|r, v| { r.trise().write(v, i2c_trise); }); self.i2c.i2c_cr1.store_reg(|r, v| r.pe().set(v)); let i2c_sr1 = self.i2c.i2c_sr1; self.i2c_er.add_fn(move || { let val = i2c_sr1.load_val(); handle_i2c_err::<I2C>(&val, i2c_sr1); fib::Yielded::<(), !>(()) }); } fn init_dma_tx(&mut self, channel: u32, priority: u32) { let address = self.i2c.i2c_dr.as_mut_ptr(); self.dma_tx.dma_cpar.store_reg(|r, v| { r.pa().write(v, address as u32); }); self.dma_tx.dma_ccr.store_reg(|r, v| { r.chsel().write(v, channel); r.pl().write(v, priority); r.msize().write(v, 0b00); r.psize().write(v, 0b00); r.minc().set(v); r.pinc().clear(v); r.dir().write(v, 0b01); r.tcie().clear(v); r.teie().set(v); }); let dma_isr_dmeif = self.dma_tx.dma_isr_dmeif; let dma_isr_feif = self.dma_tx.dma_isr_feif; let dma_isr_teif = self.dma_tx.dma_isr_teif; self.dma_tx_int.add_fn(move || { let val = dma_isr_teif.load_val(); handle_dma_err::<DmaTx>(&val, dma_isr_dmeif, dma_isr_feif, dma_isr_teif); fib::Yielded::<(), !>(()) }); } fn init_dma_rx(&mut self, channel: u32, priority: u32) { let address = self.i2c.i2c_dr.as_ptr(); self.dma_rx.dma_cpar.store_reg(|r, v| { r.pa().write(v, address as u32); }); self.dma_rx.dma_ccr.store_reg(|r, v| { r.chsel().write(v, channel); r.pl().write(v, priority); r.msize().write(v, 0b00); r.psize().write(v, 0b00); r.minc().set(v); r.pinc().clear(v); r.dir().write(v, 0b00); r.tcie().set(v); r.teie().set(v); }); } } fn handle_dma_err<T: DmaChMap>( val: &T::DmaIsrVal, dma_isr_dmeif: T::CDmaIsrDmeif, dma_isr_feif: T::CDmaIsrFeif, dma_isr_teif: T::CDmaIsrTeif, ) { if dma_isr_teif.read(&val) { panic!("Transfer error"); } if dma_isr_dmeif.read(&val) { panic!("Direct mode error"); } if dma_isr_feif.read(&val) { panic!("FIFO error"); } } fn handle_i2c_err<T: I2CMap>(val: &T::I2CSr1Val, i2c_sr1: T::CI2CSr1) { if i2c_sr1.berr().read(&val) { panic!("Misplaced Start or Stop condition"); } if i2c_sr1.arlo().read(&val) { panic!("Arbitration Lost detected"); } if i2c_sr1.af().read(&val) { panic!("Acknowledge failure"); } if i2c_sr1.ovr().read(&val) { panic!("Overrun or underrun"); } if i2c_sr1.timeout().read(&val) { panic!("SCL remained LOW for 25 ms"); } }
r.m0a().write(v, buf_rx.as_mut_ptr() as u32); }); self.dma_rx.dma_cndtr.store_reg(|r, v| { r.ndt().write(v, buf_rx.len() as u32); }); self.dma_rx.dma_ccr.modify_reg(|r, v| r.en().set(v)); future } fn start(&mut self, addr: u8, ack: bool) -> impl Future<Output = ()> { let i2c_cr1 = self.i2c.i2c_cr1; let i2c_cr2 = self.i2c.i2c_cr2; let i2c_sr1 = self.i2c.i2c_sr1; let i2c_sr2 = self.i2c.i2c_sr2; let i2c_dr = self.i2c.i2c_dr; let set_start = move || { i2c_cr1.modify_reg(|r, v| { if ack { r.ack().set(v); } else { r.ack().clear(v); } r.start().set(v); }); }; let repeated = self.i2c.i2c_sr2.msl().read_bit(); let future = self.i2c_ev.add_future(fib::new_fn(move || { let sr1_val = i2c_sr1.load_val(); if i2c_sr1.sb().read(&sr1_val) { i2c_dr.store_reg(|r, v| r.dr().write(v, u32::from(addr))); fib::Yielded(()) } else if i2c_sr1.addr().read(&sr1_val) { let sr2_val = i2c_sr2.load_val(); if i2c_sr2.tra().read(&sr2_val) { fib::Yielded(()) } else { fib::Complete(()) } } else if i2c_sr1.btf().read(&sr1_val) { if repeated { set_start(); fib::Yielded(()) } else { i2c_cr2.itevten().clear_bit(); fib::Complete(()) } } else { fib::Yielded(())
random
[ { "content": " unsafe { self.drv.read(addr, buffer).await };\n\n self\n\n }\n\n\n\n /// Returns a reference to the session buffer.\n\n // #[must_use]\n\n // pub fn buf(&self) -> &[u8] {\n\n // &self.buf\n\n // }\n\n\n\n /// Returns a mutable reference to the session buffer...
Rust
examples/echo.rs
sdroege/memfd-rs
923792d71da3cd225eaeeb7517164279aec38817
extern crate nix; extern crate getopts; extern crate memfd; use std::io; use std::os::unix::io::{RawFd, AsRawFd}; use std::path::{Path, PathBuf}; use nix::sys::socket::*; use nix::unistd::*; use nix::sys::uio::*; use getopts::Options; use std::env; use memfd::*; #[derive(Debug)] pub struct UnixDatagram { fd: RawFd, } impl UnixDatagram { pub fn new() -> io::Result<UnixDatagram> { let fd = match socket(AddressFamily::Unix, SockType::Datagram, SOCK_CLOEXEC, 0) { Ok(fd) => fd, Err(nix::Error::Sys(errno)) => { return Err(io::Error::from_raw_os_error(errno as i32)); } Err(_) => unreachable!(), }; Ok(UnixDatagram { fd: fd }) } pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixDatagram> { let datagram = try!(UnixDatagram::new()); let _ = unlink(path.as_ref()); let addr = match UnixAddr::new(path.as_ref()) { Ok(addr) => addr, Err(nix::Error::Sys(errno)) => { return Err(io::Error::from_raw_os_error(errno as i32)); } Err(_) => unreachable!(), }; match bind(datagram.fd, &SockAddr::Unix(addr)) { Ok(()) => (), Err(nix::Error::Sys(errno)) => { return Err(io::Error::from_raw_os_error(errno as i32)); } Err(_) => unreachable!(), }; Ok(datagram) } pub fn send<P: AsRef<Path>>(&self, path: P, data: &[u8], memfd: Option<&SealedMemFd>) -> io::Result<()> { let iov = [IoVec::from_slice(data)]; let addr = match UnixAddr::new(path.as_ref()) { Ok(addr) => addr, Err(nix::Error::Sys(errno)) => { return Err(io::Error::from_raw_os_error(errno as i32)); } Err(_) => unreachable!(), }; let res = match memfd { Some(fd) => { sendmsg(self.fd, &iov, &[ControlMessage::ScmRights(&[fd.as_raw_fd()])], MSG_CMSG_CLOEXEC, Some(&SockAddr::Unix(addr))) } None => { sendmsg(self.fd, &iov, &[], MsgFlags::empty(), Some(&SockAddr::Unix(addr))) } }; match res { Ok(_) => Ok(()), Err(nix::Error::Sys(errno)) => Err(io::Error::from_raw_os_error(errno as i32)), Err(_) => unreachable!(), } } pub fn recv(&self, data: &mut [u8], memfd: &mut Option<SealedMemFd>) -> io::Result<(usize, Option<PathBuf>)> { let iov = [IoVec::from_mut_slice(data)]; let mut cmsgs: CmsgSpace<[RawFd; 1]> = CmsgSpace::new(); let msg = match recvmsg(self.fd, &iov, Some(&mut cmsgs), MSG_CMSG_CLOEXEC) { Ok(msg) => msg, Err(nix::Error::Sys(errno)) => { return Err(io::Error::from_raw_os_error(errno as i32)); } Err(_) => unreachable!(), }; let path = msg.address .map(|a| { match a { SockAddr::Unix(u) => u.path().map(|p| p.to_path_buf()), _ => None, } }) .and_then(|p| p); *memfd = None; for cmsg in msg.cmsgs() { match cmsg { ControlMessage::ScmRights(fds) if fds.len() == 1 => { *memfd = Some(try!(SealedMemFd::new(fds[0]))); break; } _ => (), }; } Ok((msg.bytes, path)) } } impl Drop for UnixDatagram { fn drop(&mut self) { if self.fd != -1 { let _ = close(self.fd); } } } fn run_server<P: AsRef<Path>>(path: P) { let dg = UnixDatagram::bind(path).unwrap(); loop { let mut data = [0; 1024]; let mut memfd = None; let res = dg.recv(&mut data, &mut memfd).unwrap(); let memfd = memfd.unwrap(); println!("Received {} bytes from {:?}", res.0, res.1); println!("Data: {:?}", &data[0..res.0]); println!("MemFd size: {}", memfd.get_size().unwrap()); println!(""); } } fn run_client<P: AsRef<Path>>(path: P) { let dg = UnixDatagram::new().unwrap(); let path_ref = path.as_ref(); loop { let data = [0, 1, 2, 3, 4, 5, 6, 7]; let mut mfd = MemFd::new("echo").unwrap(); let _ = mfd.set_size(1024 * 1024).unwrap(); { let s = mfd.as_mut_slice().unwrap(); for i in 0..s.len() { s[i] = i as u8; } } let smfd = mfd.seal().unwrap(); let res = dg.send(path_ref, &data, Some(&smfd)); println!("Sent: {:?}", res); res.unwrap(); } } fn print_usage(program: &str, opts: &Options) { let brief = format!("Usage: {} FILE [options]", program); print!("{}", opts.usage(&brief)); } fn main() { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optflag("h", "help", "Help"); opts.optflag("c", "client", "Run in client mode"); opts.optflag("s", "server", "Run in server mode"); opts.reqopt("p", "path", "Path to connect to", "PATH"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()), }; if matches.opt_present("h") { print_usage(&program, &opts); return; } if matches.opt_present("c") && matches.opt_present("s") { print_usage(&program, &opts); return; } let path = match matches.opt_str("p") { Some(path) => path, None => { print_usage(&program, &opts); return; } }; if matches.opt_present("c") { run_client(&path); } else if matches.opt_present("s") { run_server(&path); } else { print_usage(&program, &opts); return; } }
extern crate nix; extern crate getopts; extern crate memfd; use std::io; use std::os::unix::io::{RawFd, AsRawFd}; use std::path::{Path, PathBuf}; use nix::sys::socket::*; use nix::unistd::*; use nix::sys::uio::*; use getopts::Options; use std::env; use memfd::*; #[derive(Debug)] pub struct UnixDatagram { fd: RawFd, } impl UnixDatagram { pub fn new() -> io::Result<UnixDatagram> { let fd = match socket(AddressFamily::Unix, SockType::Datagram, SOCK_CLOEXEC, 0) { Ok(fd) => fd, Err(nix::Error::Sys(errno)) => { return Err(io::Error::from_raw_os_error(errno as i32)); } Err(_) => unreachable!(), }; Ok(UnixDatagram { fd: fd }) } pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixDatagram> { let datagram = try!(UnixDatagram::new()); let _ = unlink(path.as_ref()); let addr = match UnixAddr::new(path.as_ref()) { Ok(addr) => addr, Err(nix::Error::Sys(errno)) => { return Err(io::Error::from_raw_os_error(errno as i32)); } Err(_) => unreachable!(), }; match bind(datagram.fd, &SockAddr::Unix(addr)) { Ok(()) => (), Err(nix::Error::Sys(errno)) => { return Err(io::Error::from_raw_os_error(errno as i32)); } Err(_) => unreachable!(), }; Ok(datagram) } pub fn send<P: AsRef<Path>>(&self, path: P, data: &[u8], memfd: Option<&SealedMemFd>) -> io::Result<()> { let iov = [IoVec::from_slice(data)]; let addr = match UnixAddr::new(path.as_ref()) { Ok(addr) => addr, Err(nix::Error::Sys(errno)) => { return Err(io::Error::from_raw_os_error(errno as i32)); } Err(_) => unreachable!(), }; let res = match memfd { Some(fd) => {
} None => { sendmsg(self.fd, &iov, &[], MsgFlags::empty(), Some(&SockAddr::Unix(addr))) } }; match res { Ok(_) => Ok(()), Err(nix::Error::Sys(errno)) => Err(io::Error::from_raw_os_error(errno as i32)), Err(_) => unreachable!(), } } pub fn recv(&self, data: &mut [u8], memfd: &mut Option<SealedMemFd>) -> io::Result<(usize, Option<PathBuf>)> { let iov = [IoVec::from_mut_slice(data)]; let mut cmsgs: CmsgSpace<[RawFd; 1]> = CmsgSpace::new(); let msg = match recvmsg(self.fd, &iov, Some(&mut cmsgs), MSG_CMSG_CLOEXEC) { Ok(msg) => msg, Err(nix::Error::Sys(errno)) => { return Err(io::Error::from_raw_os_error(errno as i32)); } Err(_) => unreachable!(), }; let path = msg.address .map(|a| { match a { SockAddr::Unix(u) => u.path().map(|p| p.to_path_buf()), _ => None, } }) .and_then(|p| p); *memfd = None; for cmsg in msg.cmsgs() { match cmsg { ControlMessage::ScmRights(fds) if fds.len() == 1 => { *memfd = Some(try!(SealedMemFd::new(fds[0]))); break; } _ => (), }; } Ok((msg.bytes, path)) } } impl Drop for UnixDatagram { fn drop(&mut self) { if self.fd != -1 { let _ = close(self.fd); } } } fn run_server<P: AsRef<Path>>(path: P) { let dg = UnixDatagram::bind(path).unwrap(); loop { let mut data = [0; 1024]; let mut memfd = None; let res = dg.recv(&mut data, &mut memfd).unwrap(); let memfd = memfd.unwrap(); println!("Received {} bytes from {:?}", res.0, res.1); println!("Data: {:?}", &data[0..res.0]); println!("MemFd size: {}", memfd.get_size().unwrap()); println!(""); } } fn run_client<P: AsRef<Path>>(path: P) { let dg = UnixDatagram::new().unwrap(); let path_ref = path.as_ref(); loop { let data = [0, 1, 2, 3, 4, 5, 6, 7]; let mut mfd = MemFd::new("echo").unwrap(); let _ = mfd.set_size(1024 * 1024).unwrap(); { let s = mfd.as_mut_slice().unwrap(); for i in 0..s.len() { s[i] = i as u8; } } let smfd = mfd.seal().unwrap(); let res = dg.send(path_ref, &data, Some(&smfd)); println!("Sent: {:?}", res); res.unwrap(); } } fn print_usage(program: &str, opts: &Options) { let brief = format!("Usage: {} FILE [options]", program); print!("{}", opts.usage(&brief)); } fn main() { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optflag("h", "help", "Help"); opts.optflag("c", "client", "Run in client mode"); opts.optflag("s", "server", "Run in server mode"); opts.reqopt("p", "path", "Path to connect to", "PATH"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()), }; if matches.opt_present("h") { print_usage(&program, &opts); return; } if matches.opt_present("c") && matches.opt_present("s") { print_usage(&program, &opts); return; } let path = match matches.opt_str("p") { Some(path) => path, None => { print_usage(&program, &opts); return; } }; if matches.opt_present("c") { run_client(&path); } else if matches.opt_present("s") { run_server(&path); } else { print_usage(&program, &opts); return; } }
sendmsg(self.fd, &iov, &[ControlMessage::ScmRights(&[fd.as_raw_fd()])], MSG_CMSG_CLOEXEC, Some(&SockAddr::Unix(addr)))
call_expression
[ { "content": " pub fn as_slice<'a>(&'a self) -> Result<&'a [u8], io::Error> {\n\n let size = try!(self.get_size());\n\n if size == 0 {\n\n return Ok(&[]);\n\n }\n\n\n\n match self.map {\n\n SealedMap::ReadOnly(p, s) => Ok(unsafe { slice::from_raw_parts(p as *...
Rust
src/router/messaging.rs
verkehrsministerium/autobahnkreuz-rs
03d194257709ad9ef1226141b052bf9c0f2408d6
use crate::router::{ConnectionHandler, ConnectionState}; use ws::{CloseCode, Handler, Message as WSMessage, Request, Response, Result as WSResult}; use crate::messages::{ErrorDetails, ErrorType, Message, Reason}; use rmp_serde::Deserializer as RMPDeserializer; use serde_json; use serde::Deserialize; use std::collections::HashMap; use std::io::Cursor; use crate::{Error, ErrorKind, WampResult, ID}; impl ConnectionHandler { pub fn send_message(&self, message: Message) { self.router.send_message(self.info_id, message) } fn handle_message(&mut self, message: Message) -> WampResult<()> { log::debug!("Received message {:?}", message); match message { Message::Hello(realm, details) => { self.handle_hello(realm, details)?; }, Message::Subscribe(request_id, options, topic) => { self.handle_subscribe(request_id, options, topic); } Message::Publish(request_id, options, topic, args, kwargs) => { self.handle_publish(request_id, options, topic, args, kwargs); } Message::Unsubscribe(request_id, topic_id) => { self.handle_unsubscribe(request_id, topic_id); } Message::Goodbye(details, reason) => { self.handle_goodbye(details, reason)?; }, Message::Register(_request_id, _options, _procedure) => { unimplemented!(); } Message::Unregister(_request_id, _procedure_id) => { unimplemented!(); } Message::Call(_request_id, _options, _procedure, _args, _kwargs) => { unimplemented!(); } Message::Yield(_invocation_id, _options, _args, _kwargs) => { unimplemented!(); } Message::Error(_e_type, _request_id, _details, _reason, _args, _kwargs) => { unimplemented!(); } t => Err(Error::new(ErrorKind::InvalidMessageType(t)))?, } Ok(()) } fn parse_message(&self, msg: WSMessage) -> WampResult<Message> { match msg { WSMessage::Text(payload) => match serde_json::from_str(&payload) { Ok(message) => Ok(message), Err(e) => Err(Error::new(ErrorKind::JSONError(e))), }, WSMessage::Binary(payload) => { let mut de = RMPDeserializer::new(Cursor::new(payload)); match Deserialize::deserialize(&mut de) { Ok(message) => Ok(message), Err(e) => Err(Error::new(ErrorKind::MsgPackError(e))), } } } } fn send_error(&self, err_type: ErrorType, request_id: ID, reason: Reason) { self.send_message(Message::Error(err_type, request_id, HashMap::new(), reason, None, None)); } fn send_abort(&self, reason: Reason) { self.send_message(Message::Abort(ErrorDetails::new(), reason)); } fn on_message_error(&self, error: Error) -> WSResult<()> { use std::error::Error as StdError; match error.get_kind() { ErrorKind::WSError(e) => Err(e)?, ErrorKind::URLError(_) => unimplemented!(), ErrorKind::HandshakeError(r) => { log::error!("Handshake error: {}", r); self.send_abort(r); self.terminate_connection()?; } ErrorKind::UnexpectedMessage(msg) => { log::error!("Unexpected Message: {}", msg); self.terminate_connection()?; } ErrorKind::ThreadError(_) => unimplemented!(), ErrorKind::ConnectionLost => unimplemented!(), ErrorKind::Closing(_) => { unimplemented!{} } ErrorKind::JSONError(e) => { log::error!("Could not parse JSON: {}", e); self.terminate_connection()?; } ErrorKind::MsgPackError(e) => { log::error!("Could not parse MsgPack: {}", e.description()); self.terminate_connection()?; } ErrorKind::MalformedData => unimplemented!(), ErrorKind::InvalidMessageType(msg) => { log::error!("Router unable to handle message {:?}", msg); self.terminate_connection()?; } ErrorKind::InvalidState(s) => { log::error!("Invalid State: {}", s); self.terminate_connection()?; } ErrorKind::Timeout => { log::error!("Connection timeout"); self.terminate_connection()?; } ErrorKind::ErrorReason(err_type, id, reason) => self.send_error(err_type, id, reason), } Ok(()) } } impl Handler for ConnectionHandler { fn on_request(&mut self, request: &Request) -> WSResult<Response> { log::info!("New request"); let mut response = match Response::from_request(request) { Ok(response) => response, Err(e) => { log::error!("Could not create response: {}", e); return Err(e); } }; self.process_protocol(request, &mut response)?; log::debug!("Sending response"); Ok(response) } fn on_message(&mut self, msg: WSMessage) -> WSResult<()> { log::debug!("Receveied message: {:?}", msg); let message = match self.parse_message(msg) { Err(e) => return self.on_message_error(e), Ok(m) => m, }; match self.handle_message(message) { Err(e) => self.on_message_error(e), _ => Ok(()), } } fn on_close(&mut self, code: CloseCode, reason: &str) { log::debug!("connection closed with {:?}: {}", code, reason); if let Ok(conn) = self.router.connection(self.info_id) { let state = conn.lock().unwrap().state.clone(); if state != ConnectionState::Disconnected { log::trace!("Client disconnected. Closing connection"); self.terminate_connection().ok(); } } } }
use crate::router::{ConnectionHandler, ConnectionState}; use ws::{CloseCode, Handler, Message as WSMessage, Request, Response, Result as WSResult}; use crate::messages::{ErrorDetails, ErrorType, Message, Reason}; use rmp_serde::Deserializer as RMPDeserializer; use serde_json; use serde::Deserialize; use std::collections::HashMap; use std::io::Cursor; use crate::{Error, ErrorKind, WampResult, ID}; impl ConnectionHandler { pub fn send_message(&self, message: Message) { self.router.send_message(self.info_id, message) } fn handle_message(&mut self, message: Message) -> WampResult<()> { log::debug!("Received message {:?}", message); match message { Message::Hello(realm, details) => { self.handle_hello(realm, details)?; }, Message::Subscribe(request_id, options, topic) => { self.handle_subscribe(request_id, options, topic); } Message::Publish(request_id, options, topic, args, kwargs) => { self.handle_publish(request_id, options, topic, args, kwargs); } Message::Unsubscribe(request_id, topic_id) => { self.handle_unsubscribe(request_id, topic_id); } Message::Goodbye(details, reason) => { self.handle_goodbye(details, reason)?; }, Message::Register(_request_id, _options, _procedure) => { unimplemented!(); } Message::Unregister(_request_id, _procedure_id) => { unimplemented!(); } Message::Call(_request_id, _options, _procedure, _args, _kwargs) => { unimplemented!(); } Message::Yield(_invocation_id, _options, _args, _kwargs) => { unimplemented!(); } Message::Error(_e_type, _request_id, _details, _reason, _args, _kwargs) => { unimplemented!(); } t => Err(Error::new(ErrorKind::InvalidMessageType(t)))?, } Ok(()) } fn parse_message(&self, msg: WSMessage) -> WampResult<Message> { match msg { WSMessage::Text(payload) => match serde_json::from_str(&payload) { Ok(message) => Ok(message), Err(e) => Err(Error::new(ErrorKind::JSONError(e))), }, WSMessage::Binary(payload) => { let mut de = RMPDeserializer::new(Cursor::new(payload)); match Deserialize::deserialize(&mut de) { Ok(message) => Ok(message), Err(e) => Err(Error::new(ErrorKind::MsgPackError(e))), } } } } fn send_error(&self, err_type: ErrorType, request_id: ID, reason: Reason) { self.send_message(Message::Error(err_type, request_id, HashMap::new(), reason, None, None)); } fn send_abort(&self, reason: Reason) { self.send_message(Message::Abort(ErrorDetails::new(), reason)); } fn on_message_error(&self, error: Error) -> WSResult<()> { use std::error::Error as StdError; match error.get_kind() { ErrorKind::WSError(e) => Err(e)?, ErrorKind::URLError(_) => unimplemented!(), ErrorKind::HandshakeError(r) => { log::error!("Handshake error: {}", r); self.send_abort(r); self.terminate_connection()?; } ErrorKind::UnexpectedMessage(msg) => { log::error!("Unexpected Message: {}", msg); self.terminate_connection()?; } ErrorKind::ThreadError(_) => unimplemented!(), ErrorKind::ConnectionLost => unimplemented!(), ErrorKind::Closing(_) => { unimplemented!{} } ErrorKind::JSONError(e) => { log::error!("Could not parse JSON: {}", e); self.terminate_connection()?; } ErrorKind::MsgPackError(e) => { log::error!("Could not parse MsgPack: {}", e.description()); self.terminate_connection()?; } ErrorKind::MalformedData => unimplemented!(), ErrorKind::InvalidMessageType(msg) => { log::error!("Router unable to handle message {:?}", msg); self.terminate_connection()?; } ErrorKind::InvalidState(s) => { log::error!("Invalid State: {}", s); self.terminate_connection()?; } ErrorKind::Timeout => { log::error!("Connection timeout"); self.terminate_connection()?; } ErrorKind::ErrorReason(err_type, id, reason) => self.send_error(err_type, id, reason), } Ok(()) } } impl Handler for ConnectionHandler { fn on_request(&mut self, request: &Request) -> WSResult<Response> { log::info!("New request"); let mut response = match Response::from_request(request) { Ok(response) => response, Err(e) => { log::error!("Could not create response: {}", e); return Err(e); } }; self.process_protocol(request, &mut response)?; log::debug!("Sending response"); Ok(response) } fn on_message(&mut self, msg: WSMessage) -> WSResult<()> { log::debug!("Receveied message: {:?}", msg);
match self.handle_message(message) { Err(e) => self.on_message_error(e), _ => Ok(()), } } fn on_close(&mut self, code: CloseCode, reason: &str) { log::debug!("connection closed with {:?}: {}", code, reason); if let Ok(conn) = self.router.connection(self.info_id) { let state = conn.lock().unwrap().state.clone(); if state != ConnectionState::Disconnected { log::trace!("Client disconnected. Closing connection"); self.terminate_connection().ok(); } } } }
let message = match self.parse_message(msg) { Err(e) => return self.on_message_error(e), Ok(m) => m, };
assignment_statement
[ { "content": "pub fn send_message_msgpack(sender: &Sender, message: &Message) -> WSResult<()> {\n\n // Send the message\n\n let mut buf: Vec<u8> = Vec::new();\n\n message\n\n .serialize(&mut Serializer::with(&mut buf, StructMapWriter))\n\n .unwrap();\n\n sender.send(WSMessage::Binary(b...
Rust
rust/strprintf/src/traits.rs
Spacewalker2/newsboat
8efc234e7d3ca6df3d0797c131eb917fe4ab18cf
use std::ffi::CString; pub trait Printfable { type Holder: CReprHolder; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder>; } impl Printfable for i32 { type Holder = i32; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self) } } impl Printfable for u32 { type Holder = u32; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self) } } impl Printfable for i64 { type Holder = i64; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self) } } impl Printfable for u64 { type Holder = u64; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self) } } impl Printfable for f32 { type Holder = f64; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self as f64) } } impl Printfable for f64 { type Holder = f64; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self) } } impl<'a> Printfable for &'a str { type Holder = CString; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { CString::new(self).ok() } } impl<'a> Printfable for &'a String { type Holder = CString; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { CString::new(self.as_str()).ok() } } impl Printfable for String { type Holder = CString; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { CString::new(self).ok() } } impl<T> Printfable for *const T { type Holder = *const libc::c_void; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self as *const libc::c_void) } } pub trait CReprHolder { type Output; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output; } impl CReprHolder for i32 { type Output = i32; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { *self } } impl CReprHolder for u32 { type Output = u32; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { *self } } impl CReprHolder for i64 { type Output = i64; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { *self } } impl CReprHolder for u64 { type Output = u64; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { *self } } impl CReprHolder for f64 { type Output = f64; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { *self } } impl CReprHolder for CString { type Output = *const libc::c_char; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { self.as_ptr() } } impl CReprHolder for *const libc::c_void { type Output = *const libc::c_void; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { *self } }
use std::ffi::CString; pub trait Printfable { type Holder: CReprHolder; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder>; } impl Printfable for i32 { type Holder = i32; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self) } } impl Printfable for u32 { type Holder = u32; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self) } } impl Printfable for i64 { type Holder = i64; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self) } } impl Printfable for u64 { type Holder = u64; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self) } } impl Printfable for f32 { type Holder = f64; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self as f64) } } impl Printfable for f64 { type Holder = f64; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self) } } impl<'a> Printfable for &'a str { type Holder = CString; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { CString::new(self).ok() } } impl<'a> Printfable for &'a String { type Holder = CString; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { CString::new(self.as_str()).ok() } } impl Printfable for String { type Holder = CString; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { CString::new(self).ok() } } impl<T> Printfable for *const T { type Holder = *const libc::c_void; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self as *const libc::c_void) } } pub trait CReprHolder { type Output; fn to_c_repr(self: &Self) -> <Self
<Self as CReprHolder>::Output { *self } } impl CReprHolder for CString { type Output = *const libc::c_char; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { self.as_ptr() } } impl CReprHolder for *const libc::c_void { type Output = *const libc::c_void; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { *self } }
as CReprHolder>::Output; } impl CReprHolder for i32 { type Output = i32; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { *self } } impl CReprHolder for u32 { type Output = u32; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { *self } } impl CReprHolder for i64 { type Output = i64; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { *self } } impl CReprHolder for u64 { type Output = u64; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { *self } } impl CReprHolder for f64 { type Output = f64; fn to_c_repr(self: &Self) ->
random
[ { "content": "pub fn to_u(rs_str: String, default_value: u32) -> u32 {\n\n let mut result = rs_str.parse::<u32>();\n\n\n\n if result.is_err() {\n\n result = Ok(default_value);\n\n }\n\n\n\n result.unwrap()\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 0, "scor...
Rust
src/bf.rs
ruslashev/bfga
673f382e2b70a86a5b661f0ffb494579e39afb61
#[derive(Clone)] pub enum BfErr { SyntaxError, InstrLimitExceeded, LogicError, } pub type BfResult = Result<(String, u64), BfErr>; impl std::fmt::Display for BfErr { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { BfErr::SyntaxError => write!(f, "syntax error"), BfErr::InstrLimitExceeded => write!(f, "instruction limit exceeded"), BfErr::LogicError => write!(f, "logic error"), } } } const TAPE_SIZE: usize = 1_000; fn check_bf_syntax(src: &Vec<char>) -> bool { let mut balance = 0; for instr in src { balance += match instr { '[' => 1, ']' => -1, _ => 0 }; if balance < 0 { return false } } balance == 0 } fn find_matching_brackets(src: &Vec<char>) -> Vec<usize> { let mut matching_brackets = vec![0; src.len()]; let mut count = 0; let mut idx_per_count = vec![0; src.len()]; for (idx, &instr) in src.iter().enumerate() { if instr == '[' { idx_per_count[count] = idx; count += 1; } else if instr == ']' { count -= 1; matching_brackets[idx_per_count[count]] = idx; matching_brackets[idx] = idx_per_count[count]; } } matching_brackets } pub fn interpret_brainfuck(src: &Vec<char>, max_intructions: u64) -> BfResult { let mut instr_ptr: usize = 0; let mut tape_ptr: usize = 0; let mut tape: [u8; TAPE_SIZE] = [0; TAPE_SIZE]; let mut num_instructions = 0; let mut output = String::from(""); if check_bf_syntax(src) == false { return Err(BfErr::SyntaxError) } let matching_brackets = find_matching_brackets(src); loop { if instr_ptr >= src.len() { break } if max_intructions != 0 { num_instructions += 1; if num_instructions > max_intructions { return Err(BfErr::InstrLimitExceeded) } } let instr: char = src[instr_ptr]; instr_ptr = match instr { '+' => { tape[tape_ptr] = tape[tape_ptr].wrapping_add(1); instr_ptr + 1 } '-' => { tape[tape_ptr] = tape[tape_ptr].wrapping_sub(1); instr_ptr + 1 } '>' => { if tape_ptr < TAPE_SIZE - 1 { tape_ptr += 1 } else { return Err(BfErr::LogicError); } instr_ptr + 1 } '<' => { if tape_ptr > 0 { tape_ptr -= 1 } else { return Err(BfErr::LogicError); } instr_ptr + 1 } '[' => { if tape[tape_ptr] == 0 { matching_brackets[instr_ptr] } else { instr_ptr + 1 } } ']' => { if tape[tape_ptr] != 0 { matching_brackets[instr_ptr] } else { instr_ptr + 1 } } '.' => { output.push(tape[tape_ptr] as char); instr_ptr + 1 } _ => instr_ptr + 1, } } Ok((output, num_instructions)) } #[test] fn hello_world_test() { let src = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.> ---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."; match interpret_brainfuck(&src.chars().collect(), 10_000) { Ok((output, _)) => assert_eq!(output, "Hello World!\n"), Err(_) => panic!("oopsie") } } #[test] fn matching_brackets_test() { let src = ".[..[]..[].]."; let expected = vec![0, 11, 0, 0, 5, 4, 0, 0, 9, 8, 0, 1, 0]; assert_eq!(expected, find_matching_brackets(&src.chars().collect())); }
#[derive(Clone)] pub enum BfErr { SyntaxError, InstrLimitExceeded, LogicError, } pub type BfResult = Result<(String, u64), BfErr>; impl std::fmt::Display for BfErr {
} const TAPE_SIZE: usize = 1_000; fn check_bf_syntax(src: &Vec<char>) -> bool { let mut balance = 0; for instr in src { balance += match instr { '[' => 1, ']' => -1, _ => 0 }; if balance < 0 { return false } } balance == 0 } fn find_matching_brackets(src: &Vec<char>) -> Vec<usize> { let mut matching_brackets = vec![0; src.len()]; let mut count = 0; let mut idx_per_count = vec![0; src.len()]; for (idx, &instr) in src.iter().enumerate() { if instr == '[' { idx_per_count[count] = idx; count += 1; } else if instr == ']' { count -= 1; matching_brackets[idx_per_count[count]] = idx; matching_brackets[idx] = idx_per_count[count]; } } matching_brackets } pub fn interpret_brainfuck(src: &Vec<char>, max_intructions: u64) -> BfResult { let mut instr_ptr: usize = 0; let mut tape_ptr: usize = 0; let mut tape: [u8; TAPE_SIZE] = [0; TAPE_SIZE]; let mut num_instructions = 0; let mut output = String::from(""); if check_bf_syntax(src) == false { return Err(BfErr::SyntaxError) } let matching_brackets = find_matching_brackets(src); loop { if instr_ptr >= src.len() { break } if max_intructions != 0 { num_instructions += 1; if num_instructions > max_intructions { return Err(BfErr::InstrLimitExceeded) } } let instr: char = src[instr_ptr]; instr_ptr = match instr { '+' => { tape[tape_ptr] = tape[tape_ptr].wrapping_add(1); instr_ptr + 1 } '-' => { tape[tape_ptr] = tape[tape_ptr].wrapping_sub(1); instr_ptr + 1 } '>' => { if tape_ptr < TAPE_SIZE - 1 { tape_ptr += 1 } else { return Err(BfErr::LogicError); } instr_ptr + 1 } '<' => { if tape_ptr > 0 { tape_ptr -= 1 } else { return Err(BfErr::LogicError); } instr_ptr + 1 } '[' => { if tape[tape_ptr] == 0 { matching_brackets[instr_ptr] } else { instr_ptr + 1 } } ']' => { if tape[tape_ptr] != 0 { matching_brackets[instr_ptr] } else { instr_ptr + 1 } } '.' => { output.push(tape[tape_ptr] as char); instr_ptr + 1 } _ => instr_ptr + 1, } } Ok((output, num_instructions)) } #[test] fn hello_world_test() { let src = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.> ---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."; match interpret_brainfuck(&src.chars().collect(), 10_000) { Ok((output, _)) => assert_eq!(output, "Hello World!\n"), Err(_) => panic!("oopsie") } } #[test] fn matching_brackets_test() { let src = ".[..[]..[].]."; let expected = vec![0, 11, 0, 0, 5, 4, 0, 0, 9, 8, 0, 1, 0]; assert_eq!(expected, find_matching_brackets(&src.chars().collect())); }
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { BfErr::SyntaxError => write!(f, "syntax error"), BfErr::InstrLimitExceeded => write!(f, "instruction limit exceeded"), BfErr::LogicError => write!(f, "logic error"), } }
function_block-full_function
[ { "content": "fn fitness(chromosome: &Chromosome, bf_result: &bf::BfResult) -> u64 {\n\n let fitness = match bf_result {\n\n Ok((output, num_instructions)) => {\n\n let diff = string_difference(&output, TARGET);\n\n let length_term =\n\n if diff == 0 {\n\n ...
Rust
meta/src/local.rs
kaiuri/rust-rosetta
67862e06956f955cdf34743a7e5c7c93e4077b64
use std::collections::HashSet; use std::fs; use std::path::{Path, PathBuf}; use anyhow::{anyhow, Context, Error}; use reqwest::Url; use toml::Value; use walkdir::WalkDir; use crate::remote; use crate::TASK_URL_RE; #[derive(Debug, Clone)] pub struct LocalTask { pub package_name: String, pub manifest_path: PathBuf, pub source: HashSet<PathBuf>, pub url: Url, pub title: String, } fn is_dylib_or_proc_macro(target: &cargo_metadata::Target) -> bool { target.kind.contains(&String::from("dylib")) || target.kind.contains(&String::from("proc-macro")) } pub fn parse_tasks<P>(manifest_path: P) -> Result<Vec<LocalTask>, Error> where P: AsRef<Path>, { let metadata = cargo_metadata::metadata(Some(manifest_path.as_ref())).unwrap(); let packages = &metadata.packages; let mut tasks = vec![]; for member in &metadata.workspace_members { if member.name() == "rust-rosetta" || member.name() == "meta" { continue; } let package = packages.iter().find(|p| p.name == member.name()).unwrap(); if package.targets.iter().any(is_dylib_or_proc_macro) { continue; } let manifest_path = Path::new(&package.manifest_path); let rosetta_url = parse_rosetta_url(manifest_path).context(format!( "could not parse rosetta code URL from {}", manifest_path.display() ))?; let title = { let caps = TASK_URL_RE.captures(rosetta_url.as_str()).ok_or_else(|| { anyhow!( "task URL does not match rosetta code regex: {}", rosetta_url ) })?; remote::decode_title(&caps[1]) }; tasks.push(LocalTask { package_name: member.name().to_owned(), manifest_path: manifest_path.to_owned(), source: find_sources(manifest_path.parent().unwrap())?, url: rosetta_url, title, }); } Ok(tasks) } fn parse_rosetta_url<P>(manifest_path: P) -> Result<Url, Error> where P: AsRef<Path>, { let manifest: Value = fs::read_to_string(manifest_path)?.parse()?; let url = manifest .get("package") .and_then(|p| p.get("metadata")) .and_then(|m| m.get("rosettacode")) .and_then(|m| m.get("url")) .and_then(|u| u.as_str()) .ok_or_else(|| anyhow!("unexpected metadata format"))?; Ok(Url::parse(url)?) } fn find_sources<P>(directory: P) -> Result<HashSet<PathBuf>, Error> where P: AsRef<Path>, { let mut sources = HashSet::new(); for entry in WalkDir::new(directory) { let entry = entry?; if let Some("rs") = entry.path().extension().and_then(|s| s.to_str()) { sources.insert(entry.path().to_owned()); } } Ok(sources) }
use std::collections::HashSet; use std::fs; use std::path::{Path, PathBuf}; use anyhow::{anyhow, Context, Error}; use reqwest::Url; use toml::Value; use walkdir::WalkDir; use crate::remote; use crate::TASK_URL_RE; #[derive(Debug, Clone)] pub struct LocalTask { pub package_name: String, pub manifest_path: PathBuf, pub source: HashSet<PathBuf>, pub url: Url, pub title: String, } fn is_dylib_or_proc_macro(target: &cargo_metadata::Target) -> bool { target.kind.contains(&String::from("dylib")) || target.kind.contains(&String::from("proc-macro")) } pub fn parse_tasks<P>(manifest_path: P) -> Result<Vec<LocalTask>, Error> where P: AsRef<Path>, { let metadata = cargo_metadata::metadata(Some(manifest_path.as_ref())).unwrap(); let packages = &metadata.packages; let mut tasks = vec![]; for member in &metadata.workspace_members { if member.name() == "rust-rosetta" || member.name() == "meta" { continue; } let package = packages.iter().find(|p| p.name == member.name()).unwrap(); if package.targets.iter().any(is_dylib_or_proc_macro) { continue; } let manifest_path = Path::new(&package.manifest_path); let rosetta_url = parse_rosetta_url(manifest_path).context(format!( "could not parse rosetta code URL from {}", manifest_path.display() ))?; let title = { let caps = TASK_URL_RE.captures(rosetta_url.as_str()).ok_or_else(|| { anyhow!( "task URL does not match rosetta code regex: {}", rosetta_url ) })?; remote::decode_title(&caps[1]) }; tasks.push(LocalTask { package_name: member.name().to_owned(), manifest_path: manifest_path.to_owned(), source: find_sources(manifest_path.parent().unwrap())?, url: rosetta_url, title, }); } Ok(tasks) }
fn find_sources<P>(directory: P) -> Result<HashSet<PathBuf>, Error> where P: AsRef<Path>, { let mut sources = HashSet::new(); for entry in WalkDir::new(directory) { let entry = entry?; if let Some("rs") = entry.path().extension().and_then(|s| s.to_str()) { sources.insert(entry.path().to_owned()); } } Ok(sources) }
fn parse_rosetta_url<P>(manifest_path: P) -> Result<Url, Error> where P: AsRef<Path>, { let manifest: Value = fs::read_to_string(manifest_path)?.parse()?; let url = manifest .get("package") .and_then(|p| p.get("metadata")) .and_then(|m| m.get("rosettacode")) .and_then(|m| m.get("url")) .and_then(|u| u.as_str()) .ok_or_else(|| anyhow!("unexpected metadata format"))?; Ok(Url::parse(url)?) }
function_block-full_function
[]
Rust
src/bin/tui/status.rs
ssneep/grin
b7e29fee55e60c1ec6fa8678b252231855b34816
use cursive::Cursive; use cursive::view::View; use cursive::views::{BoxView, LinearLayout, TextView}; use cursive::direction::Orientation; use cursive::traits::*; use tui::constants::*; use tui::types::*; use servers::ServerStats; pub struct TUIStatusView; impl TUIStatusListener for TUIStatusView { fn create() -> Box<View> { let basic_status_view = BoxView::with_full_screen( LinearLayout::new(Orientation::Vertical) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new("Current Status: ")) .child(TextView::new("Starting").with_id("basic_current_status")), ) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new("Connected Peers: ")) .child(TextView::new("0").with_id("connected_peers")), ) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new("Chain Height: ")) .child(TextView::new(" ").with_id("chain_height")), ) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new("Total Difficulty: ")) .child(TextView::new(" ").with_id("basic_total_difficulty")), ) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new("------------------------")), ) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new(" ").with_id("basic_mining_config_status")), ) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new(" ").with_id("basic_mining_status")), ) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new(" ").with_id("basic_network_info")), ), ); Box::new(basic_status_view.with_id(VIEW_BASIC_STATUS)) } fn update(c: &mut Cursive, stats: &ServerStats) { let basic_status = { if stats.is_syncing { if stats.awaiting_peers { "Waiting for peers".to_string() } else { format!("Syncing - Latest header: {}", stats.header_head.height).to_string() } } else { "Running".to_string() } }; let basic_mining_config_status = { if stats.mining_stats.is_enabled { "Configured as mining node" } else { "Configured as validating node only (not mining)" } }; let (basic_mining_status, basic_network_info) = { if stats.mining_stats.is_enabled { if stats.is_syncing { ( "Mining Status: Paused while syncing".to_string(), " ".to_string(), ) } else if stats.mining_stats.combined_gps == 0.0 { ( "Mining Status: Starting miner and awaiting first solution...".to_string(), " ".to_string(), ) } else { ( format!( "Mining Status: Mining at height {} at {:.*} GPS", stats.mining_stats.block_height, 4, stats.mining_stats.combined_gps ), format!( "Cuckoo {} - Network Difficulty {}", stats.mining_stats.cuckoo_size, stats.mining_stats.network_difficulty.to_string() ), ) } } else { (" ".to_string(), " ".to_string()) } }; c.call_on_id("basic_current_status", |t: &mut TextView| { t.set_content(basic_status); }); c.call_on_id("connected_peers", |t: &mut TextView| { t.set_content(stats.peer_count.to_string()); }); c.call_on_id("chain_height", |t: &mut TextView| { t.set_content(stats.head.height.to_string()); }); c.call_on_id("basic_total_difficulty", |t: &mut TextView| { t.set_content(stats.head.total_difficulty.to_string()); }); c.call_on_id("basic_mining_config_status", |t: &mut TextView| { t.set_content(basic_mining_config_status); }); c.call_on_id("basic_mining_status", |t: &mut TextView| { t.set_content(basic_mining_status); }); c.call_on_id("basic_network_info", |t: &mut TextView| { t.set_content(basic_network_info); }); } }
use cursive::Cursive; use cursive::view::View; use cursive::views::{BoxView, LinearLayout, TextView}; use cursive::direction::Orientation; use cursive::traits::*; use tui::constants::*; use tui::types::*; use servers::ServerStats; pub struct TUIStatusView; impl TUIStatusListener for TUIStatusView { fn create() -> Box<View> { let basic_status_view = BoxView::with_full_screen( LinearLayout::new(Orientation::Vertical) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new("Current Status: ")) .child(TextView::new("Starting").with_id("basic_current_status")), ) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new("Connected Peers: ")) .child(TextView::new("0").with_id("connected_peers")), ) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new("Chain Height: ")) .child(TextView::new(" ").with_id("chain_height")), ) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new("Total Difficulty: ")) .child(TextView::new(" ").with_id("basic_total_difficulty")), ) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new("------------------------")), ) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new(" ").with_id("basic_mining_config_status")), ) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new(" ").with_id("basic_mining_status")), ) .child( LinearLayout::new(Orientation::Horizontal) .
fn update(c: &mut Cursive, stats: &ServerStats) { let basic_status = { if stats.is_syncing { if stats.awaiting_peers { "Waiting for peers".to_string() } else { format!("Syncing - Latest header: {}", stats.header_head.height).to_string() } } else { "Running".to_string() } }; let basic_mining_config_status = { if stats.mining_stats.is_enabled { "Configured as mining node" } else { "Configured as validating node only (not mining)" } }; let (basic_mining_status, basic_network_info) = { if stats.mining_stats.is_enabled { if stats.is_syncing { ( "Mining Status: Paused while syncing".to_string(), " ".to_string(), ) } else if stats.mining_stats.combined_gps == 0.0 { ( "Mining Status: Starting miner and awaiting first solution...".to_string(), " ".to_string(), ) } else { ( format!( "Mining Status: Mining at height {} at {:.*} GPS", stats.mining_stats.block_height, 4, stats.mining_stats.combined_gps ), format!( "Cuckoo {} - Network Difficulty {}", stats.mining_stats.cuckoo_size, stats.mining_stats.network_difficulty.to_string() ), ) } } else { (" ".to_string(), " ".to_string()) } }; c.call_on_id("basic_current_status", |t: &mut TextView| { t.set_content(basic_status); }); c.call_on_id("connected_peers", |t: &mut TextView| { t.set_content(stats.peer_count.to_string()); }); c.call_on_id("chain_height", |t: &mut TextView| { t.set_content(stats.head.height.to_string()); }); c.call_on_id("basic_total_difficulty", |t: &mut TextView| { t.set_content(stats.head.total_difficulty.to_string()); }); c.call_on_id("basic_mining_config_status", |t: &mut TextView| { t.set_content(basic_mining_config_status); }); c.call_on_id("basic_mining_status", |t: &mut TextView| { t.set_content(basic_mining_status); }); c.call_on_id("basic_network_info", |t: &mut TextView| { t.set_content(basic_network_info); }); } }
child(TextView::new(" ").with_id("basic_network_info")), ), ); Box::new(basic_status_view.with_id(VIEW_BASIC_STATUS)) }
function_block-function_prefix_line
[ { "content": "pub fn unban_peer(\n\n\tbase_addr: &String,\n\n\tapi_server_port: u16,\n\n\tpeer_addr: &String,\n\n) -> Result<(), Error> {\n\n\tlet url = format!(\n\n\t\t\"http://{}:{}/v1/peers/{}/unban\",\n\n\t\tbase_addr, api_server_port, peer_addr\n\n\t);\n\n\tapi::client::post(url.as_str(), &\"\").map_err(|e...
Rust
contract/src/lib.rs
Kouprin/contracts-one
8b49f210c379227596a575a141aca7adf282c856
use regex::Regex; use std::cmp::min; use std::convert::TryInto; mod audit; mod certificate; mod contract; mod primitives; mod project; mod user; mod version; pub use crate::audit::*; pub use crate::certificate::*; pub use crate::contract::*; pub use crate::primitives::*; pub use crate::project::*; pub use crate::user::*; pub use crate::version::*; use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; use near_sdk::collections::{LookupMap, LookupSet, TreeMap, UnorderedMap, UnorderedSet}; use near_sdk::json_types::{Base58CryptoHash, ValidAccountId, WrappedTimestamp}; use near_sdk::serde::{Deserialize, Serialize}; use near_sdk::{env, near_bindgen, AccountId, Balance, CryptoHash, PanicOnDefault, Timestamp}; near_sdk::setup_alloc!(); #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize, PanicOnDefault)] pub struct Main { pub projects: UnorderedMap<ProjectId, Project>, pub contracts: TreeMap<ContractHash, Contract>, } #[near_bindgen] impl Main { #[init] pub fn new() -> Self { assert!(!env::state_exists(), "Already initialized"); let mut main = Self { projects: UnorderedMap::new(b"a".to_vec()), contracts: TreeMap::new(b"b".to_vec()), }; let mut user = main.extract_user_or_create(&env::signer_account_id()); user.is_council = true; main.save_user_or_panic(&env::signer_account_id(), &user); assert!(Self::council().insert(&env::signer_account_id())); main } } impl Main { pub(crate) fn users() -> LookupMap<UserId, User> { LookupMap::new(b"c".to_vec()) } pub(crate) fn audits() -> LookupMap<AuditId, Audit> { LookupMap::new(b"d".to_vec()) } pub(crate) fn council() -> LookupSet<UserId> { LookupSet::new(b"e".to_vec()) } pub(crate) fn is_council() -> bool { Self::council().contains(&env::predecessor_account_id()) } pub(crate) fn assert_deposit(required_deposit: Balance) { assert!( env::attached_deposit() >= required_deposit, "{}: required {}, received {}", ERR_DEPOSIT_NOT_ENOUGH, required_deposit, env::attached_deposit() ) } pub(crate) fn assert_one_yocto() { assert_eq!(env::attached_deposit(), 1, "Must be 1 yocto") } pub(crate) fn assert_council() { assert!( Self::is_council(), "{}: account {}", ERR_COUNCIL, env::predecessor_account_id() ) } pub(crate) fn assert_text_len(text: &String) { assert!( text.len() < MAX_TEXT_LENGTH, "{}: length of {} is {}, max allowed length is {}", ERR_TEXT_TOO_LONG, text, text.len(), MAX_TEXT_LENGTH, ) } pub(crate) fn assert_vec_len<T>(vec: &Vec<T>) { assert!( vec.len() < MAX_VEC_LENGTH, "{}: length of vector is {}, max allowed length is {}", ERR_VEC_TOO_LONG, vec.len(), MAX_VEC_LENGTH, ) } pub(crate) fn assert_council_or_project_owner(&self, project_name: &String) { assert!( Self::is_council() || self .projects .get(&Project::get_id(project_name)) .unwrap() .owners .contains(&env::predecessor_account_id()), "{}: account {}", ERR_COUNCIL_OR_PROJECT_OWNER, env::predecessor_account_id() ) } }
use regex::Regex; use std::cmp::min; use std::convert::TryInto; mod audit; mod certificate; mod contract; mod primitives; mod project; mod user; mod version; pub use crate::audit::*; pub use crate::certificate::*; pub use crate::contract::*; pub use crate::primitives::*; pub use crate::project::*; pub use crate::user::*; pub use crate::version::*; use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; use near_sdk::collections::{LookupMap, LookupSet, TreeMap, UnorderedMap, UnorderedSet}; use near_sdk::json_types::{Base58CryptoHash, ValidAccountId, WrappedTimestamp}; use near_sdk::serde::{Deserialize, Serialize}; use near_sdk::{env, near_bindgen, AccountId, Balance, CryptoHash, PanicOnDefault, Timestamp}; near_sdk::setup_alloc!(); #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize, PanicOnDefault)] pub struct Main { pub projects: UnorderedMap<ProjectId, Project>, pub contracts: TreeMap<ContractHash, Contract>, } #[near_bindgen] impl Main { #[init]
} impl Main { pub(crate) fn users() -> LookupMap<UserId, User> { LookupMap::new(b"c".to_vec()) } pub(crate) fn audits() -> LookupMap<AuditId, Audit> { LookupMap::new(b"d".to_vec()) } pub(crate) fn council() -> LookupSet<UserId> { LookupSet::new(b"e".to_vec()) } pub(crate) fn is_council() -> bool { Self::council().contains(&env::predecessor_account_id()) } pub(crate) fn assert_deposit(required_deposit: Balance) { assert!( env::attached_deposit() >= required_deposit, "{}: required {}, received {}", ERR_DEPOSIT_NOT_ENOUGH, required_deposit, env::attached_deposit() ) } pub(crate) fn assert_one_yocto() { assert_eq!(env::attached_deposit(), 1, "Must be 1 yocto") } pub(crate) fn assert_council() { assert!( Self::is_council(), "{}: account {}", ERR_COUNCIL, env::predecessor_account_id() ) } pub(crate) fn assert_text_len(text: &String) { assert!( text.len() < MAX_TEXT_LENGTH, "{}: length of {} is {}, max allowed length is {}", ERR_TEXT_TOO_LONG, text, text.len(), MAX_TEXT_LENGTH, ) } pub(crate) fn assert_vec_len<T>(vec: &Vec<T>) { assert!( vec.len() < MAX_VEC_LENGTH, "{}: length of vector is {}, max allowed length is {}", ERR_VEC_TOO_LONG, vec.len(), MAX_VEC_LENGTH, ) } pub(crate) fn assert_council_or_project_owner(&self, project_name: &String) { assert!( Self::is_council() || self .projects .get(&Project::get_id(project_name)) .unwrap() .owners .contains(&env::predecessor_account_id()), "{}: account {}", ERR_COUNCIL_OR_PROJECT_OWNER, env::predecessor_account_id() ) } }
pub fn new() -> Self { assert!(!env::state_exists(), "Already initialized"); let mut main = Self { projects: UnorderedMap::new(b"a".to_vec()), contracts: TreeMap::new(b"b".to_vec()), }; let mut user = main.extract_user_or_create(&env::signer_account_id()); user.is_council = true; main.save_user_or_panic(&env::signer_account_id(), &user); assert!(Self::council().insert(&env::signer_account_id())); main }
function_block-full_function
[ { "content": "#[test]\n\nfn register_project_by_not_a_user() {\n\n let mut state = State::new();\n\n state.create_alice();\n\n\n\n let contract = &state.contract;\n\n let alice = state.accounts.get(ALICE).unwrap();\n\n let outcome = call!(\n\n alice,\n\n contract.register_project(\n...
Rust
src/editor.rs
Crosse/raster
f54e52004ef889748caf2322d5bd9e25837615ef
use std::cmp; use error::{RasterError, RasterResult}; use blend::{self, BlendMode}; use Color; use Image; use position::{Position, PositionMode}; use transform; pub fn blend( image1: &Image, image2: &Image, blend_mode: BlendMode, opacity: f32, position: PositionMode, offset_x: i32, offset_y: i32, ) -> RasterResult<Image> { let opacity = if opacity > 1.0 { 1.0 } else if opacity < 0.0 { 0.0 } else { opacity }; let positioner = Position::new(position, offset_x, offset_y); let (offset_x, offset_y) = positioner.get_x_y(image1.width, image1.height, image2.width, image2.height)?; let (w1, h1) = (image1.width, image1.height); let (w2, h2) = (image2.width, image2.height); if (offset_x >= w1) || (offset_x + w2 <= 0) || (offset_y >= h1) || (offset_y + h2 <= 0) { return Err(RasterError::BlendingImageFallsOutsideCanvas); } let mut loop_start_x = 0; let canvas_start_x = offset_x; if canvas_start_x < 0 { let diff = 0 - canvas_start_x; loop_start_x += diff; } let mut loop_end_x = w2; let canvas_end_x = offset_x + w2; if canvas_end_x > w1 { let diff = canvas_end_x - w1; loop_end_x -= diff; } let mut loop_start_y = 0; let canvas_start_y = offset_y; if canvas_start_y < 0 { let diff = 0 - canvas_start_y; loop_start_y += diff; } let mut loop_end_y = h2; let canvas_end_y = offset_y + h2; if canvas_end_y > h1 { let diff = canvas_end_y - h1; loop_end_y -= diff; } match blend_mode { BlendMode::Normal => blend::normal( image1, image2, loop_start_y, loop_end_y, loop_start_x, loop_end_x, offset_x, offset_y, opacity, ), BlendMode::Difference => blend::difference( image1, image2, loop_start_y, loop_end_y, loop_start_x, loop_end_x, offset_x, offset_y, opacity, ), BlendMode::Multiply => blend::multiply( image1, image2, loop_start_y, loop_end_y, loop_start_x, loop_end_x, offset_x, offset_y, opacity, ), BlendMode::Overlay => blend::overlay( image1, image2, loop_start_y, loop_end_y, loop_start_x, loop_end_x, offset_x, offset_y, opacity, ), BlendMode::Screen => blend::screen( image1, image2, loop_start_y, loop_end_y, loop_start_x, loop_end_x, offset_x, offset_y, opacity, ), } } pub fn crop( src: &mut Image, crop_width: i32, crop_height: i32, position: PositionMode, offset_x: i32, offset_y: i32, ) -> RasterResult<()> { let positioner = Position::new(position, offset_x, offset_y); let (offset_x, offset_y) = positioner.get_x_y(src.width, src.height, crop_width, crop_height)?; let offset_x = cmp::max(0, offset_x); let offset_y = cmp::max(0, offset_y); let height2 = { let height2 = offset_y + crop_height; cmp::min(height2, src.height) }; let width2 = { let width2 = offset_x + crop_width; cmp::min(width2, src.width) }; let mut dest = Image::blank(width2 - offset_x, height2 - offset_y); for y in 0..dest.height { for x in 0..dest.width { let pixel = src.get_pixel(offset_x + x, offset_y + y)?; dest.set_pixel(x, y, &Color::rgba(pixel.r, pixel.g, pixel.b, pixel.a))?; } } src.width = dest.width; src.height = dest.height; src.bytes = dest.bytes; Ok(()) } pub fn fill(src: &mut Image, color: Color) -> RasterResult<()> { for y in 0..src.height { for x in 0..src.width { src.set_pixel(x, y, &color)?; } } Ok(()) } #[derive(Debug)] pub enum ResizeMode { Exact, ExactWidth, ExactHeight, Fit, Fill, } pub fn resize(src: &mut Image, w: i32, h: i32, mode: ResizeMode) -> RasterResult<()> { match mode { ResizeMode::Exact => transform::resize_exact(src, w, h), ResizeMode::ExactWidth => transform::resize_exact_width(src, w), ResizeMode::ExactHeight => transform::resize_exact_height(src, h), ResizeMode::Fit => transform::resize_fit(src, w, h), ResizeMode::Fill => transform::resize_fill(src, w, h), } }
use std::cmp; use error::{RasterError, RasterResult}; use blend::{self, BlendMode}; use Color; use Image; use position::{Position, PositionMode}; use transform; pub fn blend( image1: &Image, image2: &Image, blend_mode: BlendMode, opacity: f32, position: PositionMode, offset_x: i32, offset_y: i32, ) -> RasterResult<Image> { let opacity = if opacity > 1.0 { 1.0 } else if opacity < 0.0 { 0.0 } else { opacity }; let positioner = Position::new(position, offset_x, offset_y); let (offset_x, offset_y) = positioner.get_x_y(image1.widt
offset_y, opacity, ), BlendMode::Difference => blend::difference( image1, image2, loop_start_y, loop_end_y, loop_start_x, loop_end_x, offset_x, offset_y, opacity, ), BlendMode::Multiply => blend::multiply( image1, image2, loop_start_y, loop_end_y, loop_start_x, loop_end_x, offset_x, offset_y, opacity, ), BlendMode::Overlay => blend::overlay( image1, image2, loop_start_y, loop_end_y, loop_start_x, loop_end_x, offset_x, offset_y, opacity, ), BlendMode::Screen => blend::screen( image1, image2, loop_start_y, loop_end_y, loop_start_x, loop_end_x, offset_x, offset_y, opacity, ), } } pub fn crop( src: &mut Image, crop_width: i32, crop_height: i32, position: PositionMode, offset_x: i32, offset_y: i32, ) -> RasterResult<()> { let positioner = Position::new(position, offset_x, offset_y); let (offset_x, offset_y) = positioner.get_x_y(src.width, src.height, crop_width, crop_height)?; let offset_x = cmp::max(0, offset_x); let offset_y = cmp::max(0, offset_y); let height2 = { let height2 = offset_y + crop_height; cmp::min(height2, src.height) }; let width2 = { let width2 = offset_x + crop_width; cmp::min(width2, src.width) }; let mut dest = Image::blank(width2 - offset_x, height2 - offset_y); for y in 0..dest.height { for x in 0..dest.width { let pixel = src.get_pixel(offset_x + x, offset_y + y)?; dest.set_pixel(x, y, &Color::rgba(pixel.r, pixel.g, pixel.b, pixel.a))?; } } src.width = dest.width; src.height = dest.height; src.bytes = dest.bytes; Ok(()) } pub fn fill(src: &mut Image, color: Color) -> RasterResult<()> { for y in 0..src.height { for x in 0..src.width { src.set_pixel(x, y, &color)?; } } Ok(()) } #[derive(Debug)] pub enum ResizeMode { Exact, ExactWidth, ExactHeight, Fit, Fill, } pub fn resize(src: &mut Image, w: i32, h: i32, mode: ResizeMode) -> RasterResult<()> { match mode { ResizeMode::Exact => transform::resize_exact(src, w, h), ResizeMode::ExactWidth => transform::resize_exact_width(src, w), ResizeMode::ExactHeight => transform::resize_exact_height(src, h), ResizeMode::Fit => transform::resize_fit(src, w, h), ResizeMode::Fill => transform::resize_fill(src, w, h), } }
h, image1.height, image2.width, image2.height)?; let (w1, h1) = (image1.width, image1.height); let (w2, h2) = (image2.width, image2.height); if (offset_x >= w1) || (offset_x + w2 <= 0) || (offset_y >= h1) || (offset_y + h2 <= 0) { return Err(RasterError::BlendingImageFallsOutsideCanvas); } let mut loop_start_x = 0; let canvas_start_x = offset_x; if canvas_start_x < 0 { let diff = 0 - canvas_start_x; loop_start_x += diff; } let mut loop_end_x = w2; let canvas_end_x = offset_x + w2; if canvas_end_x > w1 { let diff = canvas_end_x - w1; loop_end_x -= diff; } let mut loop_start_y = 0; let canvas_start_y = offset_y; if canvas_start_y < 0 { let diff = 0 - canvas_start_y; loop_start_y += diff; } let mut loop_end_y = h2; let canvas_end_y = offset_y + h2; if canvas_end_y > h1 { let diff = canvas_end_y - h1; loop_end_y -= diff; } match blend_mode { BlendMode::Normal => blend::normal( image1, image2, loop_start_y, loop_end_y, loop_start_x, loop_end_x, offset_x,
random
[ { "content": "/// Compare two images and returns a hamming distance. A value of 0 indicates a likely similar\n\n/// picture. A value between 1 and 10 is potentially a variation. A value greater than 10 is\n\n/// likely a different image.\n\n///\n\n/// # Examples\n\n/// ```\n\n/// use raster::compare;\n\n///\n\n...
Rust
src/draw_buffer.rs
GreatAttractor/projections
95c4217162c5841f1f90160c058b279b5423ba5e
use glium::Surface; use glium::texture::{ depth_texture2d_multisample::DepthTexture2dMultisample, depth_texture2d::DepthTexture2d, texture2d_multisample::Texture2dMultisample, texture2d::Texture2d, }; use std::cell::RefCell; use std::rc::Rc; const INITIAL_DRAW_BUF_SIZE: u32 = 256; const COLOR_FORMAT: glium::texture::UncompressedFloatFormat = glium::texture::UncompressedFloatFormat::U8U8U8U8; const DEPTH_FORMAT: glium::texture::DepthFormat = glium::texture::DepthFormat::I24; const NUM_SAMPLES: u32 = 8; #[derive(Copy, Clone, PartialEq)] pub enum Sampling { Single, Multi } enum Buffers { SingleSampling(Texture2d, DepthTexture2d), MultiSampling(Texture2dMultisample, DepthTexture2dMultisample) } impl Buffers { fn sampling(&self) -> Sampling { match self { Buffers::SingleSampling(_, _) => Sampling::Single, Buffers::MultiSampling(_, _) => Sampling::Multi } } } pub struct DrawBuffer { id: imgui::TextureId, renderer: Rc<RefCell<imgui_glium_renderer::Renderer>>, display: glium::Display, draw_bufs: Buffers, storage_buf: Rc<Texture2d>, texture_copy_single_gl_prog: Rc<glium::Program>, texture_copy_multi_gl_prog: Rc<glium::Program>, unit_quad: Rc<glium::VertexBuffer<crate::data::XyVertex>> } impl DrawBuffer { pub fn set_sampling(&mut self, sampling: Sampling) { let (id, draw_bufs, storage_buf) = DrawBuffer::create( sampling, &Some(self.id), self.width(), self.height(), COLOR_FORMAT, &self.display, &mut self.renderer.borrow_mut() ); self.id = id; self.draw_bufs = draw_bufs; self.storage_buf = storage_buf; } pub fn update_storage_buf(&self) { let mut fbo = glium::framebuffer::SimpleFrameBuffer::new(&self.display, &*self.storage_buf).unwrap(); match &self.draw_bufs { Buffers::SingleSampling(draw_buf, _) => { let uniforms = uniform! { source_texture: draw_buf.sampled() }; fbo.draw( &*self.unit_quad, &glium::index::NoIndices(glium::index::PrimitiveType::TriangleFan), &self.texture_copy_single_gl_prog, &uniforms, &Default::default() ).unwrap(); }, Buffers::MultiSampling(draw_buf, _) => { let uniforms = uniform! { source_texture: draw_buf.sampled() }; fbo.draw( &*self.unit_quad, &glium::index::NoIndices(glium::index::PrimitiveType::TriangleFan), &self.texture_copy_multi_gl_prog, &uniforms, &Default::default() ).unwrap(); }, }; } pub fn storage_buf(&self) -> &Rc<Texture2d> { &self.storage_buf } pub fn frame_buf(&self) -> glium::framebuffer::SimpleFrameBuffer { match &self.draw_bufs { Buffers::SingleSampling(draw_buf, depth_buf) => glium::framebuffer::SimpleFrameBuffer::with_depth_buffer( &self.display, draw_buf, depth_buf ).unwrap(), Buffers::MultiSampling(draw_buf, depth_buf) => glium::framebuffer::SimpleFrameBuffer::with_depth_buffer( &self.display, draw_buf, depth_buf ).unwrap() } } pub fn width(&self) -> u32 { self.storage_buf.width() } pub fn height(&self) -> u32 { self.storage_buf.height() } pub fn new( sampling: Sampling, texture_copy_single_gl_prog: &Rc<glium::Program>, texture_copy_multi_gl_prog: &Rc<glium::Program>, unit_quad: &Rc<glium::VertexBuffer<crate::data::XyVertex>>, display: &glium::Display, renderer: &Rc<RefCell<imgui_glium_renderer::Renderer>> ) -> DrawBuffer { let (id, draw_bufs, storage_buf) = DrawBuffer::create( sampling, &None, INITIAL_DRAW_BUF_SIZE, INITIAL_DRAW_BUF_SIZE, COLOR_FORMAT, display, &mut renderer.borrow_mut() ); DrawBuffer { id, display: display.clone(), renderer: Rc::clone(renderer), draw_bufs, storage_buf, unit_quad: Rc::clone(unit_quad), texture_copy_single_gl_prog: Rc::clone(texture_copy_single_gl_prog), texture_copy_multi_gl_prog: Rc::clone(texture_copy_multi_gl_prog) } } pub fn new_with_size( sampling: Sampling, texture_copy_single_gl_prog: &Rc<glium::Program>, texture_copy_multi_gl_prog: &Rc<glium::Program>, unit_quad: &Rc<glium::VertexBuffer<crate::data::XyVertex>>, display: &glium::Display, renderer: &Rc<RefCell<imgui_glium_renderer::Renderer>>, width: u32, height: u32 ) -> DrawBuffer { let (id, draw_bufs, storage_buf) = DrawBuffer::create( sampling, &None, width, height, COLOR_FORMAT, display, &mut renderer.borrow_mut() ); DrawBuffer { id, display: display.clone(), renderer: Rc::clone(renderer), draw_bufs, storage_buf, unit_quad: Rc::clone(unit_quad), texture_copy_single_gl_prog: Rc::clone(texture_copy_single_gl_prog), texture_copy_multi_gl_prog: Rc::clone(texture_copy_multi_gl_prog) } } pub fn id(&self) -> imgui::TextureId { self.id } fn create( sampling: Sampling, prev_id: &Option<imgui::TextureId>, width: u32, height: u32, format: glium::texture::UncompressedFloatFormat, display: &glium::Display, renderer: &mut imgui_glium_renderer::Renderer ) -> (imgui::TextureId, Buffers, Rc<Texture2d>) { let draw_bufs = match sampling { Sampling::Single => Buffers::SingleSampling( Texture2d::empty_with_format( display, format, glium::texture::MipmapsOption::NoMipmap, width, height ).unwrap(), DepthTexture2d::empty_with_format( display, DEPTH_FORMAT, glium::texture::MipmapsOption::NoMipmap, width, height ).unwrap() ), Sampling::Multi => Buffers::MultiSampling( Texture2dMultisample::empty_with_format( display, format, glium::texture::MipmapsOption::NoMipmap, width, height, NUM_SAMPLES ).unwrap(), DepthTexture2dMultisample::empty_with_format( display, DEPTH_FORMAT, glium::texture::MipmapsOption::NoMipmap, width, height, NUM_SAMPLES ).unwrap() ) }; let storage_buf = std::rc::Rc::new(Texture2d::empty_with_format( display, glium::texture::UncompressedFloatFormat::U8U8U8, glium::texture::MipmapsOption::NoMipmap, width, height ).unwrap()); let imgui_tex = imgui_glium_renderer::Texture { texture: storage_buf.clone(), sampler: glium::uniforms::SamplerBehavior { magnify_filter: glium::uniforms::MagnifySamplerFilter::Linear, minify_filter: glium::uniforms::MinifySamplerFilter::Linear, ..Default::default() }, }; let id = match prev_id { None => renderer.textures().insert(imgui_tex), Some(prev_id) => { renderer.textures().replace(*prev_id, imgui_tex); *prev_id } }; (id, draw_bufs, storage_buf) } pub fn update_size( &mut self, width: u32, height: u32 ) -> bool { if width != self.storage_buf.width() || height != self.storage_buf.height() { let (id, draw_bufs, storage_buf) = DrawBuffer::create( self.draw_bufs.sampling(), &Some(self.id), width, height, COLOR_FORMAT, &self.display, &mut self.renderer.borrow_mut() ); self.id = id; self.draw_bufs = draw_bufs; self.storage_buf = storage_buf; true } else { false } } }
use glium::Surface; use glium::texture::{ depth_texture2d_multisample::DepthTexture2dMultisample, depth_texture2d::DepthTexture2d, texture2d_multisample::Texture2dMultisample, texture2d::Texture2d, }; use std::cell::RefCell; use std::rc::Rc; const INITIAL_DRAW_BUF_SIZE: u32 = 256; const COLOR_FORMAT: glium::texture::UncompressedFloatFormat = glium::texture::UncompressedFloatFormat::U8U8U8U8; const DEPTH_FORMAT: glium::texture::DepthFormat = glium::texture::DepthFormat::I24; const NUM_SAMPLES: u32 = 8; #[derive(Copy, Clone, PartialEq)] pub enum Sampling { Single, Multi } enum Buffers { SingleSampling(Texture2d, DepthTexture2d), MultiSampling(Texture2dMultisample, DepthTexture2dMultisample) } impl Buffers { fn sampling(&self) -> Sampling { match self { Buffers::SingleSampling(_, _) => Sampling::Single, Buffers::MultiSampling(_, _) => Sampling::Multi } } } pub struct DrawBuffer { id: imgui::TextureId, renderer: Rc<RefCell<imgui_glium_renderer::Renderer>>, display: glium::Display, draw_bufs: Buffers, storage_buf: Rc<Texture2d>, texture_copy_single_gl_prog: Rc<glium::Program>, texture_copy_multi_gl_prog: Rc<glium::Program>, unit_quad: Rc<glium::VertexBuffer<crate::data::XyVertex>> } impl DrawBuffer { pub fn set_sampling(&mut self, sampling: Sampling) { let (id, draw_bufs, storage_buf) = DrawBuffer::create( sampling, &Some(self.id), self.width(), self.height(), COLOR_FORMAT, &self.display, &mut self.renderer.borrow_mut() ); self.id = id; self.draw_bufs = draw_bufs; self.storage_buf = storage_buf; } pub fn update_storage_buf(&self) { let mut fbo = glium::framebuffer::SimpleFrameBuffer::new(&self.display, &*self.storage_buf).unwrap(); match &self.draw_bufs { Buffers::SingleSampling(draw_buf, _) => { let uniforms = uniform! { source_texture: draw_buf.sampled() }; fbo.draw( &*self.unit_quad, &glium::index::NoIndices(glium::index::PrimitiveType::TriangleFan), &self.texture_copy_single_gl_prog, &uniforms, &Default::default() ).unwrap(); }, Buffers::MultiSampling(draw_buf, _) => { let uniforms = uniform! { source_texture: draw_buf.sampled() }; fbo.draw( &*self.unit_quad, &glium::index::NoIndices(glium::index::PrimitiveType::TriangleFan), &self.texture_copy_multi_gl_prog, &uniforms, &Default::default() ).unwrap(); }, }; } pub fn storage_buf(&self) -> &Rc<Texture2d> { &self.storage_buf } pub fn frame_buf(&self) -> glium::framebuffer::SimpleFrameBuffer { match &self.draw_bufs { Buffers::SingleSampling(draw_buf, de
height, NUM_SAMPLES ).unwrap() ) }; let storage_buf = std::rc::Rc::new(Texture2d::empty_with_format( display, glium::texture::UncompressedFloatFormat::U8U8U8, glium::texture::MipmapsOption::NoMipmap, width, height ).unwrap()); let imgui_tex = imgui_glium_renderer::Texture { texture: storage_buf.clone(), sampler: glium::uniforms::SamplerBehavior { magnify_filter: glium::uniforms::MagnifySamplerFilter::Linear, minify_filter: glium::uniforms::MinifySamplerFilter::Linear, ..Default::default() }, }; let id = match prev_id { None => renderer.textures().insert(imgui_tex), Some(prev_id) => { renderer.textures().replace(*prev_id, imgui_tex); *prev_id } }; (id, draw_bufs, storage_buf) } pub fn update_size( &mut self, width: u32, height: u32 ) -> bool { if width != self.storage_buf.width() || height != self.storage_buf.height() { let (id, draw_bufs, storage_buf) = DrawBuffer::create( self.draw_bufs.sampling(), &Some(self.id), width, height, COLOR_FORMAT, &self.display, &mut self.renderer.borrow_mut() ); self.id = id; self.draw_bufs = draw_bufs; self.storage_buf = storage_buf; true } else { false } } }
pth_buf) => glium::framebuffer::SimpleFrameBuffer::with_depth_buffer( &self.display, draw_buf, depth_buf ).unwrap(), Buffers::MultiSampling(draw_buf, depth_buf) => glium::framebuffer::SimpleFrameBuffer::with_depth_buffer( &self.display, draw_buf, depth_buf ).unwrap() } } pub fn width(&self) -> u32 { self.storage_buf.width() } pub fn height(&self) -> u32 { self.storage_buf.height() } pub fn new( sampling: Sampling, texture_copy_single_gl_prog: &Rc<glium::Program>, texture_copy_multi_gl_prog: &Rc<glium::Program>, unit_quad: &Rc<glium::VertexBuffer<crate::data::XyVertex>>, display: &glium::Display, renderer: &Rc<RefCell<imgui_glium_renderer::Renderer>> ) -> DrawBuffer { let (id, draw_bufs, storage_buf) = DrawBuffer::create( sampling, &None, INITIAL_DRAW_BUF_SIZE, INITIAL_DRAW_BUF_SIZE, COLOR_FORMAT, display, &mut renderer.borrow_mut() ); DrawBuffer { id, display: display.clone(), renderer: Rc::clone(renderer), draw_bufs, storage_buf, unit_quad: Rc::clone(unit_quad), texture_copy_single_gl_prog: Rc::clone(texture_copy_single_gl_prog), texture_copy_multi_gl_prog: Rc::clone(texture_copy_multi_gl_prog) } } pub fn new_with_size( sampling: Sampling, texture_copy_single_gl_prog: &Rc<glium::Program>, texture_copy_multi_gl_prog: &Rc<glium::Program>, unit_quad: &Rc<glium::VertexBuffer<crate::data::XyVertex>>, display: &glium::Display, renderer: &Rc<RefCell<imgui_glium_renderer::Renderer>>, width: u32, height: u32 ) -> DrawBuffer { let (id, draw_bufs, storage_buf) = DrawBuffer::create( sampling, &None, width, height, COLOR_FORMAT, display, &mut renderer.borrow_mut() ); DrawBuffer { id, display: display.clone(), renderer: Rc::clone(renderer), draw_bufs, storage_buf, unit_quad: Rc::clone(unit_quad), texture_copy_single_gl_prog: Rc::clone(texture_copy_single_gl_prog), texture_copy_multi_gl_prog: Rc::clone(texture_copy_multi_gl_prog) } } pub fn id(&self) -> imgui::TextureId { self.id } fn create( sampling: Sampling, prev_id: &Option<imgui::TextureId>, width: u32, height: u32, format: glium::texture::UncompressedFloatFormat, display: &glium::Display, renderer: &mut imgui_glium_renderer::Renderer ) -> (imgui::TextureId, Buffers, Rc<Texture2d>) { let draw_bufs = match sampling { Sampling::Single => Buffers::SingleSampling( Texture2d::empty_with_format( display, format, glium::texture::MipmapsOption::NoMipmap, width, height ).unwrap(), DepthTexture2d::empty_with_format( display, DEPTH_FORMAT, glium::texture::MipmapsOption::NoMipmap, width, height ).unwrap() ), Sampling::Multi => Buffers::MultiSampling( Texture2dMultisample::empty_with_format( display, format, glium::texture::MipmapsOption::NoMipmap, width, height, NUM_SAMPLES ).unwrap(), DepthTexture2dMultisample::empty_with_format( display, DEPTH_FORMAT, glium::texture::MipmapsOption::NoMipmap, width,
random
[ { "content": "pub fn handle_gui(\n\n ui: &imgui::Ui,\n\n gui_state: &mut GuiState,\n\n program_data: &mut data::ProgramData,\n\n renderer: &Rc<RefCell<imgui_glium_renderer::Renderer>>,\n\n display: &glium::Display\n\n) {\n\n unsafe { imgui::sys::igDockSpaceOverViewport(\n\n imgui::sys::...
Rust
pallets/ai/src/lib.rs
DNFT-Team/dnft-substrate-node
f51822a2b84d4bcfc3dbcb2d1c9829f4c98582a8
#![cfg_attr(not(feature = "std"), no_std)] use codec::Encode; use frame_support::{ decl_error, decl_event, decl_module, decl_storage, ensure, traits::{Currency, Get, Randomness, Time}, StorageMap, StorageValue, }; use frame_system::ensure_signed; use pallet_randomness_collective_flip as randomness; use sp_io::hashing::blake2_256; use sp_runtime::DispatchResult; use sp_std::prelude::*; use utilities::{ AIData, AIDataId, AIModel, AIModelHighlight, AIModelId, ClassId, CollectionId, DataIndustry, DataResource, DataTechnology, ModelLanguage, NFT2006Manager, NFTId, }; type MomentOf<T> = <<T as Config>::Time as Time>::Moment; type BalanceOf<T> = <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance; pub trait Config: frame_system::Config { type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>; type NFT2006: NFT2006Manager<Self::AccountId, BalanceOf<Self>>; type Currency: Currency<Self::AccountId>; type Time: Time; } decl_event!( pub enum Event<T> where <T as frame_system::Config>::AccountId, { CreateAIData(AccountId), CreateAIModel(AccountId), BoundAIDataWithNFT(AccountId), BoundAIDataWithCollection(AccountId), BoundAIModelWithNFT(AccountId), } ); decl_error! { pub enum Error for Module<T: Config> { NoPermission, AIDataNotExist, NotAIDataOwner, NFTAlreadyBounded, NFTMintERR, CollectionAlreadyBounded, CollectionCreatERR, NotAIModelOwner, AIModelNotExist, } } decl_storage! { trait Store for Module<T: Config> as AI { pub AIDatas get(fn ai_datas): map hasher(twox_64_concat) AIDataId => Option<AIData<T::AccountId, MomentOf<T>>>; pub AIDataCount get(fn ai_data_count): u64; pub AIDataIndex get(fn ai_data_index): map hasher(blake2_128_concat) u64 => AIDataId; pub AIModels get(fn ai_models): map hasher(twox_64_concat) AIModelId => Option<AIModel<T::AccountId, MomentOf<T>>>; pub AIModelCount get(fn ai_model_count): u64; pub AIModelIndex get(fn ai_model_index): map hasher(blake2_128_concat) u64 => AIModelId; pub DNonce get(fn dnonce): u64; pub MNonce get(fn mnonce): u64; } } decl_module! { pub struct Module<T: Config> for enum Call where origin: T::Origin { type Error = Error<T>; fn deposit_event() = default; #[weight = 10_000 + T::DbWeight::get().reads_writes(1,4)] pub fn create_ai_data( origin, industry: DataIndustry, technology: DataTechnology, resource: DataResource, timestamp: MomentOf<T>, ) { let who = ensure_signed(origin)?; Self::_create_ai_data(industry, technology, resource, timestamp, who.clone())?; Self::deposit_event(RawEvent::CreateAIData(who)); } #[weight = 10_000 + T::DbWeight::get().reads_writes(1,4)] pub fn bound_ai_data_with_nft( origin, ai_data_id: AIDataId, class_id: ClassId, info: Vec<u8>, metadata: Vec<u8>, price: BalanceOf<T>, ) { let who = ensure_signed(origin)?; let ai_data = Self::ai_datas(ai_data_id.clone()).ok_or(Error::<T>::AIDataNotExist)?; ensure!(ai_data.creator == who.clone(), Error::<T>::NotAIDataOwner); ensure!(ai_data.nft_id == None, Error::<T>::NFTAlreadyBounded); let nft_id = T::NFT2006::mint_nft(class_id.clone(), info.clone(), metadata.clone(), price.clone(), who.clone()); ensure!(nft_id != None, Error::<T>::NFTMintERR); Self::_bound_ai_data_nft(ai_data_id, nft_id.unwrap())?; Self::deposit_event(RawEvent::BoundAIDataWithNFT(who)); } #[weight = 10_000 + T::DbWeight::get().reads_writes(1,4)] pub fn bound_ai_data_with_collection( origin, ai_data_id: AIDataId, collection_id: CollectionId, ) { let who = ensure_signed(origin)?; let ai_data = Self::ai_datas(ai_data_id.clone()).ok_or(Error::<T>::AIDataNotExist)?; ensure!(ai_data.creator == who.clone(), Error::<T>::NotAIDataOwner); ensure!(ai_data.collection_id == None, Error::<T>::CollectionAlreadyBounded); let collection = T::NFT2006::get_collection(collection_id.clone()); ensure!(collection != None, Error::<T>::CollectionCreatERR); ensure!(collection.unwrap().owner == who, Error::<T>::NoPermission); Self::_bound_ai_data_collection(ai_data_id, collection_id)?; Self::deposit_event(RawEvent::BoundAIDataWithCollection(who)); } #[weight = 10_000 + T::DbWeight::get().reads_writes(1,4)] pub fn create_ai_model( origin, title: Vec<u8>, language: ModelLanguage, framwork: Vec<u8>, timestamp: MomentOf<T>, highlight: Vec<AIModelHighlight>, ) { let who = ensure_signed(origin)?; Self::_create_ai_model(title, language, framwork, timestamp, highlight, who.clone())?; Self::deposit_event(RawEvent::CreateAIModel(who)); } #[weight = 10_000 + T::DbWeight::get().reads_writes(1,4)] pub fn bound_ai_model_with_nft( origin, ai_model_id: AIModelId, class_id: ClassId, info: Vec<u8>, metadata: Vec<u8>, price: BalanceOf<T>, ) { let who = ensure_signed(origin)?; let ai_model = Self::ai_models(ai_model_id.clone()).ok_or(Error::<T>::AIModelNotExist)?; ensure!(ai_model.creator == who.clone(), Error::<T>::NotAIModelOwner); ensure!(ai_model.nft_id == None, Error::<T>::NFTAlreadyBounded); let nft_id = T::NFT2006::mint_nft(class_id.clone(), info.clone(), metadata.clone(), price.clone(), who.clone()); ensure!(nft_id != None, Error::<T>::NFTMintERR); Self::_bound_ai_model_nft(ai_model_id, nft_id.unwrap())?; Self::deposit_event(RawEvent::BoundAIModelWithNFT(who)); } } } impl<T: Config> Module<T> { fn _create_ai_data( industry: DataIndustry, technology: DataTechnology, resource: DataResource, timestamp: MomentOf<T>, creator: T::AccountId, ) -> DispatchResult { let nonce = Self::get_dnonce(); let random_seed = <randomness::Module<T>>::random_seed(); let encoded = (random_seed, creator.clone(), nonce).encode(); let did = blake2_256(&encoded); let new_ai_data_id = AIDataId { did }; let new_ai_data = AIData { creator: creator.clone(), industry: industry.clone(), technology: technology.clone(), resource: resource.clone(), stars: 0, timestamp: timestamp.clone(), nft_id: None, collection_id: None, }; <AIDatas<T>>::insert(new_ai_data_id.clone(), &new_ai_data); <AIDataCount>::put(nonce.clone() + 1); <AIDataIndex>::insert(nonce.clone(), new_ai_data_id.clone()); Ok(()) } fn _bound_ai_data_nft(ai_data_id: AIDataId, nft_id: NFTId) -> DispatchResult { let mut ai_data = Self::ai_datas(ai_data_id.clone()).ok_or(Error::<T>::AIDataNotExist)?; ai_data.nft_id = Some(nft_id.clone()); <AIDatas<T>>::insert(ai_data_id.clone(), &ai_data); Ok(()) } fn _bound_ai_data_collection( ai_data_id: AIDataId, collection_id: CollectionId, ) -> DispatchResult { let mut ai_data = Self::ai_datas(ai_data_id.clone()).ok_or(Error::<T>::AIDataNotExist)?; ai_data.collection_id = Some(collection_id.clone()); <AIDatas<T>>::insert(ai_data_id.clone(), &ai_data); Ok(()) } fn get_dnonce() -> u64 { let nonce = <DNonce>::get(); <DNonce>::mutate(|n| *n += 1u64); nonce } } impl<T: Config> Module<T> { fn _create_ai_model( title: Vec<u8>, language: ModelLanguage, framwork: Vec<u8>, timestamp: MomentOf<T>, highlight: Vec<AIModelHighlight>, creator: T::AccountId, ) -> DispatchResult { let nonce = Self::get_mnonce(); let random_seed = <randomness::Module<T>>::random_seed(); let encoded = (random_seed, creator.clone(), nonce).encode(); let did = blake2_256(&encoded); let new_ai_model_id = AIModelId { did }; let new_ai_model = AIModel { creator: creator.clone(), title: title.clone(), language: language.clone(), framwork: framwork.clone(), stars: 0, timestamp: timestamp.clone(), highlight: highlight.clone(), nft_id: None, }; <AIModels<T>>::insert(new_ai_model_id.clone(), &new_ai_model); <AIModelCount>::put(nonce.clone() + 1); <AIModelIndex>::insert(nonce.clone(), new_ai_model_id.clone()); Ok(()) } fn _bound_ai_model_nft(ai_model_id: AIModelId, nft_id: NFTId) -> DispatchResult { let mut ai_model = Self::ai_models(ai_model_id.clone()).ok_or(Error::<T>::AIModelNotExist)?; ai_model.nft_id = Some(nft_id.clone()); <AIModels<T>>::insert(ai_model_id.clone(), &ai_model); Ok(()) } fn get_mnonce() -> u64 { let nonce = <MNonce>::get(); <MNonce>::mutate(|n| *n += 1u64); nonce } }
#![cfg_attr(not(feature = "std"), no_std)] use codec::Encode; use frame_support::{ decl_error, decl_event, decl_module, decl_storage, ensure, traits::{Currency, Get, Randomness, Time}, StorageMap, StorageValue, }; use frame_system::ensure_signed; use pallet_randomness_collective_flip as randomness; use sp_io::hashing::blake2_256; use sp_runtime::DispatchResult; use sp_std::prelude::*; use utilities::{ AIData, AIDataId, AIModel, AIModelHighlight, AIModelId, ClassId, CollectionId, DataIndustry, DataResource, DataTechnology, ModelLanguage, NFT2006Manager, NFTId, }; type MomentOf<T> = <<T as Config>::Time as Time>::Moment; type BalanceOf<T> = <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance; pub trait Config: frame_system::Config { type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>; type NFT2006: NFT2006Manager<Self::AccountId, BalanceOf<Self>>; type Currency: Currency<Self::AccountId>; type Time: Time; } decl_event!( pub enum Event<T> where <T as frame_system::Config>::AccountId, { CreateAIData(AccountId), CreateAIModel(AccountId), BoundAIDataWithNFT(AccountId), BoundAIDataWithCollection(AccountId), BoundAIModelWithNFT(AccountId), } ); decl_error! { pub enum Error for Module<T: Config> { NoPermission, AIDataNotExist, NotAIDataOwner, NFTAlreadyBounded, NFTMintERR, CollectionAlreadyBounded, CollectionCreatERR, NotAIModelOwner, AIModelNotExist, } } decl_storage! { trait Store for Module<T: Config> as AI { pub AIDatas get(fn ai_datas): map hasher(twox_64_concat) AIDataId => Option<AIData<T::AccountId, MomentOf<T>>>; pub AIDataCount get(fn ai_data_count): u64; pub AIDataIndex get(fn ai_data_index): map hasher(blake2_128_concat) u64 => AIDataId; pub AIModels get(fn ai_models): map hasher(twox_64_concat) AIModelId => Option<AIModel<T::AccountId, MomentOf<T>>>; pub AIModelCount get(fn ai_model_count): u64; pub AIModelIndex get(fn ai_model_index): map hasher(blake2_128_concat) u64 => AIModelId; pub DNonce get(fn dnonce): u64; pub MNonce get(fn mnonce): u64; } } decl_module! { pub struct Module<T: Config> for enum Call where origin: T::Origin { type Error = Error<T>; fn deposit_event() = default; #[weight = 10_000 + T::DbWeight::get().reads_writes(1,4)] pub fn create_ai_data( origin, industry: DataIndustry, technology: DataTechnology, resource: DataResource, timestamp: MomentOf<T>, ) { let who = ensure_signed(origin)?; Self::_create_ai_data(industry, technology, resource, timestamp, who.clone())?; Self::deposit_event(RawEvent::CreateAIData(who)); } #[weight = 10_000 + T::DbWeight::get().reads_writes(1,4)] pub fn bound_ai_data_with_nft( origin, ai_data_id: AIDataId, class_id: ClassId, info: Vec<u8>, metadata: Vec<u8>, price: BalanceOf<T>, ) { let who = ensure_signed(origin)?; let ai_data = Self::ai_datas(ai_data_id.clone()).ok_or(Error::<T>::AIDataNotExist)?; ensure!(ai_data.creator == who.clone(), Error::<T>::NotAIDataOwner); ensure!(ai_data.nft_id == None, Error::<T>::NFTAlreadyBounded); let nft_id = T::NFT2006::mint_nft(class_id.clone(), info.clone(), metadata.clone(), price.clone(), who.clone()); ensure!(nft_id != None, Error::<T>::NFTMintERR); Self::_bound_ai_data_nft(ai_data_id, nft_id.unwrap())?; Self::deposit_event(RawEvent::BoundAIDataWithNFT(who)); } #[weight = 10_000 + T::DbWeight::get().reads_writes(1,4)] pub fn bound_ai_data_with_collection( origin, ai_data_id: AIDataId, collection_id: CollectionId, ) { let who = ensure_signed(origin)?; let ai_data = Self::ai_datas(ai_data_id.clone()).ok_or(Error::<T>::AIDataNotExist)?; ensure!(ai_data.creator == who.clone(), Error::<T>::NotAIDataOwner); ensure!(ai_data.collection_id == None, Error::<T>::CollectionAlreadyBounded); let collection = T::NFT2006::get_collection(collection_id.clone()); ensure!(collection != None, Error::<T>::CollectionCreatERR); ensure!(collection.unwrap().owner == who, Error::<T>::NoPermission); Self::_bound_ai_data_collection(ai_data_id, collection_id)?; Self::deposit_event(RawEvent::BoundAIDataWithCollection(who)); } #[weight = 10_000 + T::DbWeight::get().reads_writes(1,4)] pub fn create_ai_model( origin, title: Vec<u8>, language: ModelLanguage, framwork: Vec<u8>, timestamp: MomentOf<T>, highlight: Vec<AIModelHighlight>, ) { let who = ensure_signed(origin)?; Self::_create_ai_model(title, language, framwork, timestamp, highlight, who.clone())?; Self::deposit_event(RawEvent::CreateAIModel(who)); } #[weight = 10_000 + T::DbWeight::get().reads_writes(1,4)] pub fn bound_ai_model_with_nft( origin, ai_model_id: AIModelId, class_id: ClassId, info: Vec<u8>, metadata: Vec<u8>, price: BalanceOf<T>, ) { let who = ensure_signed(origin)?; let ai_model = Self::ai_models(ai_model_id.clone()).ok_or(Error::<T>::AIModelNotExist)?; ensure!(ai_model.creator == who.clone(), Error::<T>::NotAIModelOwner); ensure!(ai_model.nft_id == None, Error::<T>::NFTAlreadyBounded); let nft_id = T::NFT2006::mint_nft(class_id.clone(), info.clone(), metadata.clone(), price.clone(), who.clone()); ensure!(nft_id != None, Error::<T>::NFTMintERR); Self::_bound_ai_model_nft(ai_model_id, nft_id.unwrap())?; Self::deposit_event(RawEvent::BoundAIModelWithNFT(who)); } } } impl<T: Config> Module<T> { fn _create_ai_data( industry: DataIndustry, technology: DataTechnology, resource: DataResource, timestamp: MomentOf<T>, creator: T::AccountId, ) -> DispatchResult { let nonce = Self::get_dnonce(); let random_seed = <randomness::Module<T>>::random_seed(); let encoded = (random_seed, creator.clone(), nonce).encode(); let did = blake2_256(&encoded); let new_ai_data_id = AIDataId { did }; let new_ai_data = AIData { creator: creator.clone(), industry: industry.clone(), technology: technology.clone(), resource: resource.clone(), stars: 0, timestamp: timestamp.clone(), nft_id: None, collection_id: None, }; <AIDatas<T>>::insert(new_ai_data_id.clone(), &new_ai_data); <AIDataCount>::put(nonce.clone() + 1); <AIDataIndex>::insert(nonce.clone(), new_ai_data_id.clone()); Ok(()) } fn _bound_ai_data_nft(ai_data_id: AIDataId, nft_id: NFTId) -> DispatchResult { let mut ai_data = Self::ai_datas(ai_data_id.clone()).ok_or(Error::<T>::AIDataNotExist)?; ai_data.nft_id = Some(nft_id.clone()); <AIDatas<T>>::insert(ai_data_id.clone(), &ai_data); Ok(()) }
fn get_dnonce() -> u64 { let nonce = <DNonce>::get(); <DNonce>::mutate(|n| *n += 1u64); nonce } } impl<T: Config> Module<T> { fn _create_ai_model( title: Vec<u8>, language: ModelLanguage, framwork: Vec<u8>, timestamp: MomentOf<T>, highlight: Vec<AIModelHighlight>, creator: T::AccountId, ) -> DispatchResult { let nonce = Self::get_mnonce(); let random_seed = <randomness::Module<T>>::random_seed(); let encoded = (random_seed, creator.clone(), nonce).encode(); let did = blake2_256(&encoded); let new_ai_model_id = AIModelId { did }; let new_ai_model = AIModel { creator: creator.clone(), title: title.clone(), language: language.clone(), framwork: framwork.clone(), stars: 0, timestamp: timestamp.clone(), highlight: highlight.clone(), nft_id: None, }; <AIModels<T>>::insert(new_ai_model_id.clone(), &new_ai_model); <AIModelCount>::put(nonce.clone() + 1); <AIModelIndex>::insert(nonce.clone(), new_ai_model_id.clone()); Ok(()) } fn _bound_ai_model_nft(ai_model_id: AIModelId, nft_id: NFTId) -> DispatchResult { let mut ai_model = Self::ai_models(ai_model_id.clone()).ok_or(Error::<T>::AIModelNotExist)?; ai_model.nft_id = Some(nft_id.clone()); <AIModels<T>>::insert(ai_model_id.clone(), &ai_model); Ok(()) } fn get_mnonce() -> u64 { let nonce = <MNonce>::get(); <MNonce>::mutate(|n| *n += 1u64); nonce } }
fn _bound_ai_data_collection( ai_data_id: AIDataId, collection_id: CollectionId, ) -> DispatchResult { let mut ai_data = Self::ai_datas(ai_data_id.clone()).ok_or(Error::<T>::AIDataNotExist)?; ai_data.collection_id = Some(collection_id.clone()); <AIDatas<T>>::insert(ai_data_id.clone(), &ai_data); Ok(()) }
function_block-full_function
[ { "content": "pub trait Config: frame_system::Config {\n\n type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>;\n\n type Currency: Currency<Self::AccountId>;\n\n type Token: TokenManager<Self::AccountId>;\n\n}\n\n\n\ndecl_event!(\n\n pub enum Event<T> where\n\n <T as f...
Rust
packages/storage-plus/src/iter_helpers.rs
DragonSBFinance/terra_smartcontract
9cfa31192a1b7d72c1ba95cca76a50befa030623
#![cfg(feature = "iterator")] use serde::de::DeserializeOwned; use cosmwasm_std::Pair; use cosmwasm_std::{from_slice, StdResult}; use crate::helpers::encode_length; pub(crate) fn deserialize_kv<T: DeserializeOwned>(kv: Pair) -> StdResult<Pair<T>> { let (k, v) = kv; let t = from_slice::<T>(&v)?; Ok((k, t)) } #[allow(dead_code)] pub(crate) fn to_length_prefixed(namespace: &[u8]) -> Vec<u8> { let mut out = Vec::with_capacity(namespace.len() + 2); out.extend_from_slice(&encode_length(namespace)); out.extend_from_slice(namespace); out } #[inline] pub(crate) fn trim(namespace: &[u8], key: &[u8]) -> Vec<u8> { key[namespace.len()..].to_vec() } #[inline] pub(crate) fn concat(namespace: &[u8], key: &[u8]) -> Vec<u8> { let mut k = namespace.to_vec(); k.extend_from_slice(key); k } #[cfg(test)] mod test { use super::*; #[test] fn to_length_prefixed_works() { assert_eq!(to_length_prefixed(b""), b"\x00\x00"); assert_eq!(to_length_prefixed(b"a"), b"\x00\x01a"); assert_eq!(to_length_prefixed(b"ab"), b"\x00\x02ab"); assert_eq!(to_length_prefixed(b"abc"), b"\x00\x03abc"); } #[test] fn to_length_prefixed_works_for_long_prefix() { let long_namespace1 = vec![0; 256]; let prefix1 = to_length_prefixed(&long_namespace1); assert_eq!(prefix1.len(), 256 + 2); assert_eq!(&prefix1[0..2], b"\x01\x00"); let long_namespace2 = vec![0; 30000]; let prefix2 = to_length_prefixed(&long_namespace2); assert_eq!(prefix2.len(), 30000 + 2); assert_eq!(&prefix2[0..2], b"\x75\x30"); let long_namespace3 = vec![0; 0xFFFF]; let prefix3 = to_length_prefixed(&long_namespace3); assert_eq!(prefix3.len(), 0xFFFF + 2); assert_eq!(&prefix3[0..2], b"\xFF\xFF"); } #[test] #[should_panic(expected = "only supports namespaces up to length 0xFFFF")] fn to_length_prefixed_panics_for_too_long_prefix() { let limit = 0xFFFF; let long_namespace = vec![0; limit + 1]; to_length_prefixed(&long_namespace); } #[test] fn to_length_prefixed_calculates_capacity_correctly() { let key = to_length_prefixed(b""); assert_eq!(key.capacity(), key.len()); let key = to_length_prefixed(b"h"); assert_eq!(key.capacity(), key.len()); let key = to_length_prefixed(b"hij"); assert_eq!(key.capacity(), key.len()); } } #[cfg(test)] #[cfg(not(feature = "iterator"))] mod namespace_test { use super::*; use cosmwasm_std::testing::MockStorage; #[test] fn test_range() { let mut storage = MockStorage::new(); let prefix = to_length_prefixed(b"foo"); let other_prefix = to_length_prefixed(b"food"); set_with_prefix(&mut storage, &prefix, b"bar", b"none"); set_with_prefix(&mut storage, &prefix, b"snowy", b"day"); set_with_prefix(&mut storage, &other_prefix, b"moon", b"buggy"); let mut iter = range_with_prefix(&storage, &prefix, None, None, Order::Descending); let first = iter.next().unwrap(); assert_eq!(first, (b"snowy".to_vec(), b"day".to_vec())); let second = iter.next().unwrap(); assert_eq!(second, (b"bar".to_vec(), b"none".to_vec())); assert!(iter.next().is_none()); let iter = storage.range(None, None, Order::Ascending); assert_eq!(3, iter.count()); let mut iter = storage.range(None, None, Order::Ascending); let first = iter.next().unwrap(); let expected_key = concat(&prefix, b"bar"); assert_eq!(first, (expected_key, b"none".to_vec())); } #[test] fn test_range_with_prefix_wrapover() { let mut storage = MockStorage::new(); let prefix = to_length_prefixed(b"f\xff\xff"); let other_prefix = to_length_prefixed(b"f\xff\x44"); set_with_prefix(&mut storage, &prefix, b"bar", b"none"); set_with_prefix(&mut storage, &prefix, b"snowy", b"day"); set_with_prefix(&mut storage, &other_prefix, b"moon", b"buggy"); let iter = range_with_prefix(&storage, &prefix, None, None, Order::Descending); let elements: Vec<Pair> = iter.collect(); assert_eq!( elements, vec![ (b"snowy".to_vec(), b"day".to_vec()), (b"bar".to_vec(), b"none".to_vec()), ] ); } #[test] fn test_range_with_start_end_set() { let mut storage = MockStorage::new(); let prefix = to_length_prefixed(b"f\xff\xff"); let other_prefix = to_length_prefixed(b"f\xff\x44"); set_with_prefix(&mut storage, &prefix, b"bar", b"none"); set_with_prefix(&mut storage, &prefix, b"snowy", b"day"); set_with_prefix(&mut storage, &other_prefix, b"moon", b"buggy"); let res: Vec<Pair> = range_with_prefix(&storage, &prefix, Some(b"b"), Some(b"c"), Order::Ascending) .collect(); assert_eq!(res.len(), 1); assert_eq!(res[0], (b"bar".to_vec(), b"none".to_vec())); let res: Vec<Pair> = range_with_prefix( &storage, &prefix, Some(b"bas"), Some(b"sno"), Order::Ascending, ) .collect(); assert_eq!(res.len(), 0); let res: Vec<Pair> = range_with_prefix(&storage, &prefix, Some(b"ant"), None, Order::Ascending).collect(); assert_eq!(res.len(), 2); assert_eq!(res[0], (b"bar".to_vec(), b"none".to_vec())); assert_eq!(res[1], (b"snowy".to_vec(), b"day".to_vec())); } #[test] fn test_namespace_upper_bound() { assert_eq!(namespace_upper_bound(b"bob"), b"boc".to_vec()); assert_eq!(namespace_upper_bound(b"fo\xfe"), b"fo\xff".to_vec()); assert_eq!(namespace_upper_bound(b"fo\xff"), b"fp\x00".to_vec()); assert_eq!( namespace_upper_bound(b"fo\xff\xff\xff"), b"fp\x00\x00\x00".to_vec() ); assert_eq!(namespace_upper_bound(b"\xffabc"), b"\xffabd".to_vec()); } }
#![cfg(feature = "iterator")] use serde::de::DeserializeOwned; use cosmwasm_std::Pair; use cosmwasm_std::{from_slice, StdResult}; use crate::helpers::encode_length; pub(crate) fn deserialize_kv<T: DeserializeOwned>(kv: Pair) -> StdResult<Pair<T>> { let (k, v) = kv; let t = from_slice::<T>(&v)?; Ok((k, t)) } #[allow(dead_code)] pub(crate) fn to_length_prefixed(namespace: &[u8]) -> Vec<u8> { let mut out = Vec::with_capacity(namespace.len() + 2); out.extend_from_slice(&encode_length(namespace)); out.extend_from_slice(namespace); out } #[inline] pub(crate) fn trim(namespace: &[u8], key: &[u8]) -> Vec<u8> { key[namespace.len()..].to_vec() } #[inline] pub(crate) fn concat(namespace: &[u8], key: &[u8]) -> Vec<u8> { let mut k = namespace.to_vec(); k.extend_from_slice(key); k } #[cfg(test)] mod test { use super::*; #[test] fn to_length_prefixed_works() { assert_eq!(to_length_prefixed(b""), b"\x00\x00"); assert_eq!(to_length_prefixed(b"a"), b"\x00\x01a"); assert_eq!(to_length_prefixed(b"ab"), b"\x00\x02ab"); assert_eq!(to_length_prefixed(b"abc"), b"\x00\x03abc"); } #[test] fn to_length_prefixed_works_for_long_prefix() { let long_namespace1 = vec![0; 256]; let prefix1 = to_length_prefixed(&long_namespace1); assert_eq!(prefix1.len(), 256 + 2); assert_eq!(&prefix1[0..2], b"\x01\x00"); let long_namespace2 = vec![0; 30000]; let prefix2 = to_length_prefixed(&long_namespace2); assert_eq!(prefix2.len(), 30000 + 2); assert_eq!(&prefix2[0..2], b"\x75\x30"); let long_namespace3 = vec![0; 0xFFFF]; let prefix3 = to_length_prefixed(&long_namespace3); assert_eq!(prefix3.len(), 0xFFFF + 2); assert_eq!(&prefix3[0..2], b"\xFF\xFF"); } #[test] #[should_panic(expected = "only supports namespaces up to length 0xFFFF")] fn to_length_prefixed_panics_for_too_long_prefix() { let limit = 0xFFFF; let long_namespace = vec![0; limit + 1]; to_length_prefixed(&long_namespace); } #[test] fn to_length_prefixed_calculates_capacity_correctly() { let key = to_length_prefixed(b""); assert_eq!(key.capacity(), key.len()); let key = to_length_prefixed(b"h"); assert_eq!(key.capacity(), key.len()); let key = to_length_prefixed(b"hij"); assert_eq!(key.capacity(), key.len()); } } #[cfg(test)] #[cfg(not(feature = "iterator"))] mod namespace_test { use super::*; use cosmwasm_std::testing::MockStorage; #[test] fn test_range() { let mut storage = MockStorage::new(); let prefix = to_length_prefixed(b"foo"); let other_prefix = to_length_prefixed(b"food"); set_with_prefix(&mut storage, &prefix, b"bar", b"none"); set_with_prefix(&mut storage, &prefix, b"snowy", b"day"); set_with_prefix(&mut storage, &other_prefix, b"moon", b"buggy"); let mut iter = range_with_prefix(&storage, &prefix, None, None, Order::Descending); let first = iter.next().unwrap(); assert_eq!(first, (b"snowy".to_vec(), b"day".to_vec())); let second = iter.next().unwrap(); assert_eq!(second, (b"bar".to_vec(), b"none".to_vec())); assert!(iter.next().is_none()); let iter = storage.range(None, None, Order::Ascending); assert_eq!(3, iter.count()); let mut iter = storage.range(None, None, Order::Ascending); let first = iter.next().unwrap(); let expected_key = concat(&prefix, b"bar"); assert_eq!(first, (expected_key, b"none".to_vec())); } #[test] fn test_range_with_prefix_wrapover() { let mut storage = MockStorage::new(); let prefix = to_length_prefixed(b"f\xff\xff"); let other_prefix = to_length_prefixed(b"f\xff\x44"); set_with_prefix(&mut storage, &prefix, b"bar", b"none"); set_with_prefix(&mut storage, &prefix, b"snowy", b"day"); set_with_prefix(&mut storage, &other_prefix, b"moon", b"buggy"); let iter = range_with_prefix(&storage, &prefix, None, None, Order::Descending); let elements: Vec<Pair> = iter.collect(); assert_eq!( elements, vec![ (b"snowy".to_vec(), b"day".to_vec()), (b"bar".to_vec(), b"none".to_vec()), ] ); } #[test] fn test_range_with_start_end_set() { let mut storage = MockStorage::new(); let prefix = to_length_prefixed(b"f\xff\xff"); let other_prefix = to_length_prefixed(b"f\xff\x44"); set_with_prefix(&mut storage, &prefix, b"bar", b"none"); set_with_prefix(&mut storage, &prefix, b"snowy", b"day"); set_with_prefix(&mut storage, &other_prefix, b"moon", b"buggy"); let res: Vec<Pair> = range_with_prefix(&storage, &prefix, Some(b"b"), Some(b"c"), Order::Ascending) .collect(); assert_eq!(res.len(), 1); assert_eq!(res[0], (b"bar".to_vec(), b"none".to_vec())); let res: Vec<Pair> =
.collect(); assert_eq!(res.len(), 0); let res: Vec<Pair> = range_with_prefix(&storage, &prefix, Some(b"ant"), None, Order::Ascending).collect(); assert_eq!(res.len(), 2); assert_eq!(res[0], (b"bar".to_vec(), b"none".to_vec())); assert_eq!(res[1], (b"snowy".to_vec(), b"day".to_vec())); } #[test] fn test_namespace_upper_bound() { assert_eq!(namespace_upper_bound(b"bob"), b"boc".to_vec()); assert_eq!(namespace_upper_bound(b"fo\xfe"), b"fo\xff".to_vec()); assert_eq!(namespace_upper_bound(b"fo\xff"), b"fp\x00".to_vec()); assert_eq!( namespace_upper_bound(b"fo\xff\xff\xff"), b"fp\x00\x00\x00".to_vec() ); assert_eq!(namespace_upper_bound(b"\xffabc"), b"\xffabd".to_vec()); } }
range_with_prefix( &storage, &prefix, Some(b"bas"), Some(b"sno"), Order::Ascending, )
call_expression
[ { "content": "fn one_byte_higher(limit: &[u8]) -> Vec<u8> {\n\n let mut v = limit.to_vec();\n\n v.push(0);\n\n v\n\n}\n\n\n", "file_path": "packages/storage-plus/src/prefix.rs", "rank": 0, "score": 360298.9457943783 }, { "content": "/// Returns a new vec of same length and last byte...
Rust
src/base/codec/decode.rs
sergeyboyko0791/redis-asio
8de643fddb2353a68f48b15b20943c9d9fa59d8d
use super::{RedisResult, RedisError, RedisErrorKind, RespInternalValue}; use std::io::Cursor; use std::error::Error; use byteorder::ReadBytesExt; pub struct ParseResult<T> { pub value: T, pub value_src_len: usize, } pub type OptParseResult<T> = Option<ParseResult<T>>; pub fn parse_resp_value(data: &[u8]) -> RedisResult<OptParseResult<RespInternalValue>> { let value_id = match Cursor::new(data).read_u8() { Ok(x) => x, Err(_) => return Ok(None) }; let data = &data[1..]; let opt_parse_result = match value_id { resp_start_bytes::ERROR => parse_error(data), resp_start_bytes::STATUS => parse_status(data), resp_start_bytes::INT => parse_int(data), resp_start_bytes::BULK_STRING => parse_bulkstring(data), resp_start_bytes::ARRAY => parse_array(data), _ => Err(RedisError::new( RedisErrorKind::ParseError, format!("Unknown RESP start byte {}", value_id))) }?; Ok(opt_parse_result .map( |ParseResult { value, value_src_len }| { let value_src_len = value_src_len + 1; ParseResult { value, value_src_len } } ) ) } mod resp_start_bytes { pub const ERROR: u8 = b'-'; pub const STATUS: u8 = b'+'; pub const INT: u8 = b':'; pub const BULK_STRING: u8 = b'$'; pub const ARRAY: u8 = b'*'; } const CRLF: (u8, u8) = (b'\r', b'\n'); const CRLF_LEN: usize = 2; fn parse_error(data: &[u8]) -> RedisResult<OptParseResult<RespInternalValue>> { parse_simple_string(data) .map(|opt_parse_result| opt_parse_result.map(|ParseResult { value, value_src_len }| { let value = RespInternalValue::Error(value); ParseResult { value, value_src_len } })) } fn parse_status(data: &[u8]) -> RedisResult<OptParseResult<RespInternalValue>> { parse_simple_string(data) .map(|opt_parse_result| opt_parse_result.map(|ParseResult { value, value_src_len }| { let value = RespInternalValue::Status(value); ParseResult { value, value_src_len } })) } fn parse_int(data: &[u8]) -> RedisResult<OptParseResult<RespInternalValue>> { parse_simple_int(data) .map(|opt_parse_result| opt_parse_result.map(|ParseResult { value, value_src_len }| { let value = RespInternalValue::Int(value); ParseResult { value, value_src_len } })) } fn parse_bulkstring(data: &[u8]) -> RedisResult<OptParseResult<RespInternalValue>> { let does_end_with_crlf = |data: &[u8]| data.ends_with(&[CRLF.0, CRLF.1]); let make_parse_error = || RedisError::new( RedisErrorKind::ParseError, "An actual data within a bulk string does not end with the CRLF".to_string()); let ParseResult { value, value_src_len: len_len } = match parse_simple_int(data)? { Some(x) => x, _ => return Ok(None), }; if value < 0 { if data.len() < len_len + CRLF_LEN { return Ok(None); } match does_end_with_crlf(&data[..len_len + CRLF_LEN]) { true => return Ok(Some( ParseResult { value: RespInternalValue::Nil, value_src_len: len_len + CRLF_LEN })), false => return Err(make_parse_error()) }; } let string_len = value as usize; let value_src_len = len_len + string_len + CRLF_LEN; if data.len() < value_src_len { return Ok(None); } if !data[..value_src_len].ends_with(&[CRLF.0, CRLF.1]) { return Err(make_parse_error()); } let value_data = data[len_len..len_len + string_len].to_vec(); let value = RespInternalValue::BulkString(value_data); Ok(Some(ParseResult { value, value_src_len })) } fn parse_array(data: &[u8]) -> RedisResult<OptParseResult<RespInternalValue>> { let ParseResult { value: array_len, value_src_len: len_len } = match parse_simple_int(data)? { Some(x) => x, _ => return Ok(None), }; if array_len < 0 { return Ok(Some(ParseResult { value: RespInternalValue::Nil, value_src_len: len_len })); } let array_len = array_len as usize; let mut pos = len_len; let mut result: Vec<RespInternalValue> = Vec::with_capacity(array_len); for _ in 0..array_len { let ParseResult { value, value_src_len } = match parse_resp_value(&data[pos..])? { Some(x) => x, _ => return Ok(None), }; result.push(value); pos = pos + value_src_len; }; Ok(Some(ParseResult { value: RespInternalValue::Array(result), value_src_len: pos })) } fn parse_simple_string(data: &[u8]) -> RedisResult<OptParseResult<String>> { let string_src_len = match data.iter().position(|x| *x == CRLF.0) { Some(x) => x, _ => return Ok(None), }; if string_src_len >= data.len() - 1 { return Ok(None); } if data[string_src_len + 1] != CRLF.1 { return Err(RedisError::new( RedisErrorKind::ParseError, "A status or an Error does not contain the CRLF".to_string())); } match String::from_utf8(data[0..string_src_len].to_vec()) { Ok(value) => { let value_src_len = string_src_len + CRLF_LEN; Ok(Some(ParseResult { value, value_src_len })) } Err(err) => Err( RedisError::new( RedisErrorKind::ParseError, format!("Could not parse a status from bytes: {}", err.description())) ) } } fn parse_simple_int(data: &[u8]) -> RedisResult<OptParseResult<i64>> { let opt_parse_result = parse_simple_string(data)?; let ParseResult { value, value_src_len } = match opt_parse_result { Some(x) => x, _ => return Ok(None), }; let value = match value.parse::<i64>() { Ok(x) => x, Err(err) => return Err( RedisError::new( RedisErrorKind::ParseError, format!("Could not parse an i64 from the {:?}, error: {}", value, err.description()), ) ), }; Ok(Some(ParseResult { value, value_src_len })) } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_status() { let data = Vec::from("+OK\r\n"); let ParseResult { value, value_src_len } = parse_resp_value(data.as_slice()).unwrap().unwrap(); assert_eq!(RespInternalValue::Status("OK".to_string()), value); assert_eq!(data.len(), value_src_len); assert!(parse_resp_value(Vec::from("+OK\r").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("+OK\r$").as_mut_slice()).is_err(), "expected Err"); } #[test] fn test_parse_error() { let data = Vec::from("-Error\r\n"); let ParseResult { value, value_src_len } = parse_resp_value(data.as_slice()).unwrap().unwrap(); assert_eq!(RespInternalValue::Error("Error".to_string()), value); assert_eq!(data.len(), value_src_len); assert!(parse_resp_value(Vec::from("-Error\r").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("-Error\r$").as_mut_slice()).is_err(), "expected Err"); } #[test] fn test_parse_int() { let data = Vec::from(":-12345\r\n"); let ParseResult { value, value_src_len } = parse_resp_value(data.as_slice()).unwrap().unwrap(); assert_eq!(RespInternalValue::Int(-12345i64), value); assert_eq!(data.len(), value_src_len); assert!(parse_resp_value(Vec::from(":-12345\r").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from(":-12345\r$").as_mut_slice()).is_err(), "expected Err"); assert!(parse_resp_value(Vec::from(":-12X45\r\n").as_mut_slice()).is_err(), "expected Err"); } #[test] fn test_parse_bulkstring() { let origin_msg = "foo\r\nbar".to_string(); let mut raw_data = format!("${}\r\n{}\r\n", origin_msg.len(), origin_msg).into_bytes(); let expected_value_len = raw_data.len(); raw_data.append(&mut "trash".as_bytes().to_vec()); let ParseResult { value, value_src_len } = parse_resp_value(raw_data.as_slice()).unwrap().unwrap(); assert_eq!(RespInternalValue::BulkString(origin_msg.into_bytes()), value); assert_eq!(expected_value_len, value_src_len); assert!(parse_resp_value(Vec::from("$7\r").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("$7\r\n$").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("$7\r\n1234567\r$").as_mut_slice()).is_err(), "expected Err"); } #[test] fn test_parse_bulkstring_nil() { let mut raw_data = Vec::from("$-10\r\n\r\n"); let expected_value_len = raw_data.len(); raw_data.append(&mut "trash".as_bytes().to_vec()); let ParseResult { value, value_src_len } = parse_resp_value(raw_data.as_slice()).unwrap().unwrap(); assert_eq!(RespInternalValue::Nil, value); assert_eq!(expected_value_len, value_src_len); assert!(parse_resp_value(Vec::from("$-10\r").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("$-10\r\n$").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("$-10\r\n%$").as_mut_slice()).is_err(), "expected Err"); } #[test] fn test_parse_array() { let mut nil_value_data = Vec::from("$-1\r\n\r\n"); let mut error_value_data = Vec::from("-Error message\r\n"); let mut status_value_data = Vec::from("+Status message\r\n"); let mut int_value_data = Vec::from(":-1423\r\n"); let mut bulkstring_value_data = Vec::from("$20\r\nBulk\r\nstring\tmessage\r\n"); let mut array_value_data = Vec::from("*3\r\n:1\r\n:2\r\n:3\r\n"); let mut array_data: Vec<u8> = Vec::from("*6\r\n"); array_data.append(&mut nil_value_data); array_data.append(&mut error_value_data); array_data.append(&mut status_value_data); array_data.append(&mut int_value_data); array_data.append(&mut bulkstring_value_data); array_data.append(&mut array_value_data); let expected_value_len = array_data.len(); array_data.append(&mut "trash".as_bytes().to_vec()); let origin = RespInternalValue::Array( vec![RespInternalValue::Nil, RespInternalValue::Error("Error message".to_string()), RespInternalValue::Status("Status message".to_string()), RespInternalValue::Int(-1423), RespInternalValue::BulkString("Bulk\r\nstring\tmessage".as_bytes().to_vec()), RespInternalValue::Array(vec![RespInternalValue::Int(1), RespInternalValue::Int(2), RespInternalValue::Int(3)]) ]); let ParseResult { value, value_src_len } = parse_resp_value(&array_data).unwrap().unwrap(); assert_eq!(origin, value); assert_eq!(expected_value_len, value_src_len); } #[test] fn test_parse_array_empty() { let mut array_data: Vec<u8> = Vec::from("0\r\n"); let expected_value_len = array_data.len(); array_data.append(&mut "trash".as_bytes().to_vec()); let origin = RespInternalValue::Array(Vec::new()); let ParseResult { value, value_src_len } = parse_array(&array_data).unwrap().unwrap(); assert_eq!(origin, value); assert_eq!(expected_value_len, value_src_len); } #[test] fn test_parse_array_boundaries() { assert!(parse_resp_value(Vec::from("*7\r").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("*7\r\n*").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("*1\r\n$").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("*1\r#$").as_mut_slice()).is_err(), "expected Err"); assert!(parse_resp_value(Vec::from("*1\r\n:12\r$").as_mut_slice()).is_err(), "expected Err"); } }
use super::{RedisResult, RedisError, RedisErrorKind, RespInternalValue}; use std::io::Cursor; use std::error::Error; use byteorder::ReadBytesExt; pub struct ParseResult<T> { pub value: T, pub value_src_len: usize, } pub type OptParseResult<T> = Option<ParseResult<T>>; pub fn parse_resp_value(data: &[u8]) -> RedisResult<OptParseResult<RespInternalValue>> { let value_id = match Cursor::new(data).read_u8() { Ok(x) => x, Err(_) => return Ok(None) }; let data = &data[1..]; let opt_parse_result = match value_id { resp_start_bytes::ERROR => parse_error(data), resp_start_bytes::STATUS => parse_status(data), resp_start_bytes::INT => parse_int(data), resp_start_bytes::BULK_STRING => parse_bulkstring(data), resp_start_bytes::ARRAY => parse_array(data), _ => Err(RedisError::new( RedisErrorKind::ParseError, format!("Unknown RESP start byte {}", value_id))) }?; Ok(opt_parse_result .map( |ParseResult { value, value_src_len }| { let value_src_len = value_src_len + 1; ParseResult { value, value_src_len } } ) ) } mod resp_start_bytes { pub const ERROR: u8 = b'-'; pub const STATUS: u8 = b'+'; pub const INT: u8 = b':'; pub const BULK_STRING: u8 = b'$'; pub const ARRAY: u8 = b'*'; } const CRLF: (u8, u8) = (b'\r', b'\n'); const CRLF_LEN: usize = 2;
fn parse_status(data: &[u8]) -> RedisResult<OptParseResult<RespInternalValue>> { parse_simple_string(data) .map(|opt_parse_result| opt_parse_result.map(|ParseResult { value, value_src_len }| { let value = RespInternalValue::Status(value); ParseResult { value, value_src_len } })) } fn parse_int(data: &[u8]) -> RedisResult<OptParseResult<RespInternalValue>> { parse_simple_int(data) .map(|opt_parse_result| opt_parse_result.map(|ParseResult { value, value_src_len }| { let value = RespInternalValue::Int(value); ParseResult { value, value_src_len } })) } fn parse_bulkstring(data: &[u8]) -> RedisResult<OptParseResult<RespInternalValue>> { let does_end_with_crlf = |data: &[u8]| data.ends_with(&[CRLF.0, CRLF.1]); let make_parse_error = || RedisError::new( RedisErrorKind::ParseError, "An actual data within a bulk string does not end with the CRLF".to_string()); let ParseResult { value, value_src_len: len_len } = match parse_simple_int(data)? { Some(x) => x, _ => return Ok(None), }; if value < 0 { if data.len() < len_len + CRLF_LEN { return Ok(None); } match does_end_with_crlf(&data[..len_len + CRLF_LEN]) { true => return Ok(Some( ParseResult { value: RespInternalValue::Nil, value_src_len: len_len + CRLF_LEN })), false => return Err(make_parse_error()) }; } let string_len = value as usize; let value_src_len = len_len + string_len + CRLF_LEN; if data.len() < value_src_len { return Ok(None); } if !data[..value_src_len].ends_with(&[CRLF.0, CRLF.1]) { return Err(make_parse_error()); } let value_data = data[len_len..len_len + string_len].to_vec(); let value = RespInternalValue::BulkString(value_data); Ok(Some(ParseResult { value, value_src_len })) } fn parse_array(data: &[u8]) -> RedisResult<OptParseResult<RespInternalValue>> { let ParseResult { value: array_len, value_src_len: len_len } = match parse_simple_int(data)? { Some(x) => x, _ => return Ok(None), }; if array_len < 0 { return Ok(Some(ParseResult { value: RespInternalValue::Nil, value_src_len: len_len })); } let array_len = array_len as usize; let mut pos = len_len; let mut result: Vec<RespInternalValue> = Vec::with_capacity(array_len); for _ in 0..array_len { let ParseResult { value, value_src_len } = match parse_resp_value(&data[pos..])? { Some(x) => x, _ => return Ok(None), }; result.push(value); pos = pos + value_src_len; }; Ok(Some(ParseResult { value: RespInternalValue::Array(result), value_src_len: pos })) } fn parse_simple_string(data: &[u8]) -> RedisResult<OptParseResult<String>> { let string_src_len = match data.iter().position(|x| *x == CRLF.0) { Some(x) => x, _ => return Ok(None), }; if string_src_len >= data.len() - 1 { return Ok(None); } if data[string_src_len + 1] != CRLF.1 { return Err(RedisError::new( RedisErrorKind::ParseError, "A status or an Error does not contain the CRLF".to_string())); } match String::from_utf8(data[0..string_src_len].to_vec()) { Ok(value) => { let value_src_len = string_src_len + CRLF_LEN; Ok(Some(ParseResult { value, value_src_len })) } Err(err) => Err( RedisError::new( RedisErrorKind::ParseError, format!("Could not parse a status from bytes: {}", err.description())) ) } } fn parse_simple_int(data: &[u8]) -> RedisResult<OptParseResult<i64>> { let opt_parse_result = parse_simple_string(data)?; let ParseResult { value, value_src_len } = match opt_parse_result { Some(x) => x, _ => return Ok(None), }; let value = match value.parse::<i64>() { Ok(x) => x, Err(err) => return Err( RedisError::new( RedisErrorKind::ParseError, format!("Could not parse an i64 from the {:?}, error: {}", value, err.description()), ) ), }; Ok(Some(ParseResult { value, value_src_len })) } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_status() { let data = Vec::from("+OK\r\n"); let ParseResult { value, value_src_len } = parse_resp_value(data.as_slice()).unwrap().unwrap(); assert_eq!(RespInternalValue::Status("OK".to_string()), value); assert_eq!(data.len(), value_src_len); assert!(parse_resp_value(Vec::from("+OK\r").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("+OK\r$").as_mut_slice()).is_err(), "expected Err"); } #[test] fn test_parse_error() { let data = Vec::from("-Error\r\n"); let ParseResult { value, value_src_len } = parse_resp_value(data.as_slice()).unwrap().unwrap(); assert_eq!(RespInternalValue::Error("Error".to_string()), value); assert_eq!(data.len(), value_src_len); assert!(parse_resp_value(Vec::from("-Error\r").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("-Error\r$").as_mut_slice()).is_err(), "expected Err"); } #[test] fn test_parse_int() { let data = Vec::from(":-12345\r\n"); let ParseResult { value, value_src_len } = parse_resp_value(data.as_slice()).unwrap().unwrap(); assert_eq!(RespInternalValue::Int(-12345i64), value); assert_eq!(data.len(), value_src_len); assert!(parse_resp_value(Vec::from(":-12345\r").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from(":-12345\r$").as_mut_slice()).is_err(), "expected Err"); assert!(parse_resp_value(Vec::from(":-12X45\r\n").as_mut_slice()).is_err(), "expected Err"); } #[test] fn test_parse_bulkstring() { let origin_msg = "foo\r\nbar".to_string(); let mut raw_data = format!("${}\r\n{}\r\n", origin_msg.len(), origin_msg).into_bytes(); let expected_value_len = raw_data.len(); raw_data.append(&mut "trash".as_bytes().to_vec()); let ParseResult { value, value_src_len } = parse_resp_value(raw_data.as_slice()).unwrap().unwrap(); assert_eq!(RespInternalValue::BulkString(origin_msg.into_bytes()), value); assert_eq!(expected_value_len, value_src_len); assert!(parse_resp_value(Vec::from("$7\r").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("$7\r\n$").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("$7\r\n1234567\r$").as_mut_slice()).is_err(), "expected Err"); } #[test] fn test_parse_bulkstring_nil() { let mut raw_data = Vec::from("$-10\r\n\r\n"); let expected_value_len = raw_data.len(); raw_data.append(&mut "trash".as_bytes().to_vec()); let ParseResult { value, value_src_len } = parse_resp_value(raw_data.as_slice()).unwrap().unwrap(); assert_eq!(RespInternalValue::Nil, value); assert_eq!(expected_value_len, value_src_len); assert!(parse_resp_value(Vec::from("$-10\r").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("$-10\r\n$").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("$-10\r\n%$").as_mut_slice()).is_err(), "expected Err"); } #[test] fn test_parse_array() { let mut nil_value_data = Vec::from("$-1\r\n\r\n"); let mut error_value_data = Vec::from("-Error message\r\n"); let mut status_value_data = Vec::from("+Status message\r\n"); let mut int_value_data = Vec::from(":-1423\r\n"); let mut bulkstring_value_data = Vec::from("$20\r\nBulk\r\nstring\tmessage\r\n"); let mut array_value_data = Vec::from("*3\r\n:1\r\n:2\r\n:3\r\n"); let mut array_data: Vec<u8> = Vec::from("*6\r\n"); array_data.append(&mut nil_value_data); array_data.append(&mut error_value_data); array_data.append(&mut status_value_data); array_data.append(&mut int_value_data); array_data.append(&mut bulkstring_value_data); array_data.append(&mut array_value_data); let expected_value_len = array_data.len(); array_data.append(&mut "trash".as_bytes().to_vec()); let origin = RespInternalValue::Array( vec![RespInternalValue::Nil, RespInternalValue::Error("Error message".to_string()), RespInternalValue::Status("Status message".to_string()), RespInternalValue::Int(-1423), RespInternalValue::BulkString("Bulk\r\nstring\tmessage".as_bytes().to_vec()), RespInternalValue::Array(vec![RespInternalValue::Int(1), RespInternalValue::Int(2), RespInternalValue::Int(3)]) ]); let ParseResult { value, value_src_len } = parse_resp_value(&array_data).unwrap().unwrap(); assert_eq!(origin, value); assert_eq!(expected_value_len, value_src_len); } #[test] fn test_parse_array_empty() { let mut array_data: Vec<u8> = Vec::from("0\r\n"); let expected_value_len = array_data.len(); array_data.append(&mut "trash".as_bytes().to_vec()); let origin = RespInternalValue::Array(Vec::new()); let ParseResult { value, value_src_len } = parse_array(&array_data).unwrap().unwrap(); assert_eq!(origin, value); assert_eq!(expected_value_len, value_src_len); } #[test] fn test_parse_array_boundaries() { assert!(parse_resp_value(Vec::from("*7\r").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("*7\r\n*").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("*1\r\n$").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("*1\r#$").as_mut_slice()).is_err(), "expected Err"); assert!(parse_resp_value(Vec::from("*1\r\n:12\r$").as_mut_slice()).is_err(), "expected Err"); } }
fn parse_error(data: &[u8]) -> RedisResult<OptParseResult<RespInternalValue>> { parse_simple_string(data) .map(|opt_parse_result| opt_parse_result.map(|ParseResult { value, value_src_len }| { let value = RespInternalValue::Error(value); ParseResult { value, value_src_len } })) }
function_block-full_function
[ { "content": "pub fn encode_resp_value(value: RespInternalValue) -> Vec<u8> {\n\n match value {\n\n RespInternalValue::Nil => \"$-1\\r\\n\".as_bytes().to_vec(),\n\n RespInternalValue::Error(x) => format!(\"-{}\\r\\n\", x).into_bytes(),\n\n RespInternalValue::Status(x) => format!(\"+{}\\r...
Rust
src/global/logging.rs
HristoKolev/xdxd-snapshot-rotator
6cc807819d7a1002ab15bc087f90bbb2caa4013b
use std::sync::Mutex; use std::path::{PathBuf, Path}; use std::fs::{File, OpenOptions}; use std::io::{SeekFrom, Write, Seek}; use chrono::Utc; use super::prelude::*; pub struct LoggingConfiguration { pub max_length: u64, pub file_path: PathBuf, } pub struct FileAppenderState { file_handle: File, file_length: u64, } pub struct FileAppender { state: Mutex<FileAppenderState>, config: LoggingConfiguration, } impl FileAppender { pub fn new(config: LoggingConfiguration) -> Result<FileAppender> { ::std::fs::create_dir_all(config.file_path.get_directory())?; let mut file_handle = FileAppender::create_file_handle(&config.file_path)?; let file_length = file_handle.seek(SeekFrom::End(0))?; Ok(FileAppender { state: Mutex::new(FileAppenderState { file_handle, file_length, }), config, }) } fn create_file_handle(file_path: &Path) -> Result<File> { let file_handle = OpenOptions::new() .write(true) .create(true) .open(file_path)?; Ok(file_handle) } fn roll_file(&self, state: &mut FileAppenderState) -> Result { let file_stem = self.config.file_path.file_stem_as_string()?; let file_extension = self.config.file_path.extension_as_string()?; let directory = self.config.file_path.get_directory_as_string()?; let now = Utc::now(); let formatted_date = now.format("%Y_%m_%d__").to_string(); let nanos = now.timestamp_nanos(); let new_file_path= format!("{}/{}__{}{}.{}", directory, file_stem, formatted_date, nanos, file_extension); let new_path = Path::new(&new_file_path); state.file_handle.sync_all()?; ::std::fs::rename(&self.config.file_path, new_path)?; let file_handle = FileAppender::create_file_handle(&self.config.file_path)?; state.file_handle = file_handle; state.file_length = 0; Ok(()) } pub fn writeln(&self, message: &str) -> Result { let mut state = self.state.lock()?; if state.file_length >= self.config.max_length { self.roll_file(&mut state)?; } let len = state.file_handle.write(format!("{}\n", message).as_bytes())? as u64; state.file_length += len; Ok(()) } } pub struct ConsoleAppender; impl ConsoleAppender { pub fn new() -> ConsoleAppender { ConsoleAppender {} } #[allow(unused)] pub fn writeln(&self, message: &str) -> Result { let stdout = &mut ::std::io::stdout(); write!(stdout, "{}\n", message)?; Ok(()) } #[allow(unused)] pub fn ewriteln(&self, message: &str) -> Result { let stderr = &mut ::std::io::stderr(); write!(stderr, "{}\n", message)?; Ok(()) } } pub struct InMemoryAppender { pub entries: Mutex<Vec<String>>, } impl InMemoryAppender { pub fn new() -> InMemoryAppender { InMemoryAppender { entries: Mutex::new(Vec::new()) } } pub fn add_entry(&self, message: &str) -> Result { let mut vec = self.entries.lock()?; vec.push(message.to_string()); Ok(()) } } pub struct Logger { file_appender: FileAppender, console_appender: ConsoleAppender, in_memory_appender: InMemoryAppender, } impl Logger { pub fn new(config: LoggingConfiguration) -> Result<Logger> { Ok(Logger { console_appender: ConsoleAppender::new(), in_memory_appender: InMemoryAppender::new(), file_appender: FileAppender::new(config)? }) } fn format_message(&self, message: &str) -> Result<String> { let now = Utc::now(); let formatted_date = now.format("%Y-%m-%d %H:%M:%S").to_string(); Ok(format!("{} | {}", formatted_date, message)) } pub fn log(&self, message: &str) -> Result { let formatted_message = self.format_message(message)?; let console_appender_result = self.console_appender.writeln(&formatted_message); let in_memory_appender_result = self.in_memory_appender.add_entry(message); let file_appender_result = self.file_appender.writeln(&formatted_message); console_appender_result?; in_memory_appender_result?; file_appender_result?; Ok(()) } #[allow(unused)] pub fn elog(&self, message: &str) -> Result { let formatted_message = self.format_message(message)?; let console_appender_result = self.console_appender.ewriteln(&formatted_message); let in_memory_appender_result = self.in_memory_appender.add_entry(message); let file_appender_result = self.file_appender.writeln(&formatted_message); console_appender_result?; in_memory_appender_result?; file_appender_result?; Ok(()) } #[allow(unused)] pub fn get_logs(&self) -> Result<Vec<String>> { let logs = self.in_memory_appender.entries.lock()?; Ok(logs.clone()) } }
use std::sync::Mutex; use std::path::{PathBuf, Path}; use std::fs::{File, OpenOptions}; use std::io::{SeekFrom, Write, Seek}; use chrono::Utc; use super::prelude::*; pub struct LoggingConfiguration { pub max_length: u64, pub file_path: PathBuf, } pub struct FileAppenderState { file_handle: File, file_length: u64, } pub struct FileAppender { state: Mutex<FileAppenderState>, config: LoggingConfiguration, } impl FileAppender { pub fn new(config: LoggingConfiguration) -> Result<FileAppender> { ::std::fs::create_dir_all(config.file_path.get_directory())?; let mut file_handle = FileAppender::create_file_handle(&config.file_path)?; let file_length = file_handle.seek(SeekFrom::End(0))?; Ok(FileAppender { state: Mutex::new(FileAppenderState { file_handle, file_length, }), config, }) } fn create_file_handle(file_path: &Path) -> Result<File> { let file_handle = OpenOptions::new() .write(true) .create(true) .open(file_path)?; Ok(file_handle) } fn roll_file(&self, state: &mut FileAppenderState) -> Result { let file_stem = self.config.file_path.file_stem_as_string()?; let file_extension = self.config.file_path.extension_as_string()?; let directory = self.config.file_path.get_directory_as_string()?; let now = Utc::now(); let formatted_date = now.format("%Y_%m_%d__").to_string(); let nanos = now.timestamp_nanos(); let new_file_path= format!("{}/{}__{}{}.{}", directory, file_stem, formatted_date, nanos, file_extension); let new_path = Path::new(&new_file_path); state.file_handle.sync_all()?; ::std::fs::rename(&self.config.file_path, new_path)?; let file_handle = FileAppender::create_file_handle(&self.config.file_path)?; state.file_handle = file_handle; state.file_length = 0; Ok(()) } pub fn writeln(&self, message: &str) -> Result { let mut state = self.state.lock()?; if state.file_length >= self.config.max_length { self.roll_file(&mut state)?; } let len = state.file_handle.write(format!("{}\n", message).as_bytes())? as u64; state.file_length += len; Ok(()) } } pub struct ConsoleAppender; impl ConsoleAppender { pub fn new() -> ConsoleAppender { ConsoleAppender {} } #[allow(unused)] pub fn writeln(&self, message: &str) -> Result { let stdout = &mut ::std::io::stdout(); write!(stdout, "{}\n", message)?; Ok(()) } #[allow(unused)] pub fn ewriteln(&self, message: &str) -> Result { let stderr = &mut ::std::io::stderr(); write!(stderr, "{}\n", message)?; Ok(()) } } pub struct InMemoryAppender { pub entries: Mutex<Vec<String>>, } impl InMemoryAppender { pub fn new() -> InMemoryAppender { InMemoryAppender { entries: Mutex::new(Vec::new()) } } pub fn add_entry(&self, message: &str) -> Result { let mut vec = self.entries.lock()?; vec.push(message.to_string()); Ok(()) } } pub struct Logger { file_appender: FileAppender, console_appender: ConsoleAppender, in_memory_appender: InMemoryAppender, } impl Logger { pub fn new(config: LoggingConfiguration) -> Result<Logger> {
} fn format_message(&self, message: &str) -> Result<String> { let now = Utc::now(); let formatted_date = now.format("%Y-%m-%d %H:%M:%S").to_string(); Ok(format!("{} | {}", formatted_date, message)) } pub fn log(&self, message: &str) -> Result { let formatted_message = self.format_message(message)?; let console_appender_result = self.console_appender.writeln(&formatted_message); let in_memory_appender_result = self.in_memory_appender.add_entry(message); let file_appender_result = self.file_appender.writeln(&formatted_message); console_appender_result?; in_memory_appender_result?; file_appender_result?; Ok(()) } #[allow(unused)] pub fn elog(&self, message: &str) -> Result { let formatted_message = self.format_message(message)?; let console_appender_result = self.console_appender.ewriteln(&formatted_message); let in_memory_appender_result = self.in_memory_appender.add_entry(message); let file_appender_result = self.file_appender.writeln(&formatted_message); console_appender_result?; in_memory_appender_result?; file_appender_result?; Ok(()) } #[allow(unused)] pub fn get_logs(&self) -> Result<Vec<String>> { let logs = self.in_memory_appender.entries.lock()?; Ok(logs.clone()) } }
Ok(Logger { console_appender: ConsoleAppender::new(), in_memory_appender: InMemoryAppender::new(), file_appender: FileAppender::new(config)? })
call_expression
[ { "content": "#[allow(unused)]\n\npub fn wait_for_lock(file_path: &str) -> Result<File> {\n\n loop {\n\n if let Some(file) = lock_file(file_path)? {\n\n return Ok(file);\n\n }\n\n\n\n std::thread::sleep(Duration::from_millis(100));\n\n }\n\n}\n", "file_path": "src/globa...
Rust
crates/components/token/erc20/tests/mocks/erc20_mock.rs
zl910627/metis
b38193188614f9bd8391a6afed1a876495d0a771
#![cfg_attr(not(feature = "std"), no_std)] #[metis_lang::contract] pub mod erc20_contract { use super::super::behavior; pub use erc20::{ Error, Result, }; use metis_erc20 as erc20; use metis_lang::{ import, metis, }; #[ink(storage)] #[import(erc20)] pub struct Erc20 { erc20: erc20::Data<Erc20>, } #[cfg(not(feature = "ink-as-dependency"))] impl erc20::Impl<Erc20> for Erc20 {} type Event = <Erc20 as ink_lang::BaseEvent>::Type; #[ink(event)] #[metis(erc20)] pub struct Transfer { #[ink(topic)] pub from: Option<AccountId>, #[ink(topic)] pub to: Option<AccountId>, pub value: Balance, } #[ink(event)] #[metis(erc20)] pub struct Approval { #[ink(topic)] pub owner: AccountId, #[ink(topic)] pub spender: AccountId, pub value: Balance, } impl behavior::IERC20New<Erc20> for Erc20 { fn new_erc20( name: String, symbol: String, decimals: u8, initial_supply: Balance, ) -> Self { Self::new(name, symbol, decimals, initial_supply) } fn next_call_by(account: AccountId) { let callee = ink_env::account_id::<ink_env::DefaultEnvironment>() .unwrap_or([0x0; 32].into()); let mut data = ink_env::test::CallData::new(ink_env::call::Selector::new([0x00; 4])); data.push_arg(&account.clone()); ink_env::test::push_execution_context::<ink_env::DefaultEnvironment>( account.clone(), callee, 1000000, 1000000, data, ); } } impl behavior::IERC20Event<Erc20> for Erc20 { fn decode_transfer_event( event: &ink_env::test::EmittedEvent, ) -> (Option<AccountId>, Option<AccountId>, Balance) { let decoded_event = <Event as scale::Decode>::decode(&mut &event.data[..]) .expect("encountered invalid contract event data buffer"); if let Event::Transfer(Transfer { from, to, value }) = decoded_event { return (from, to, value) } panic!("encountered unexpected event kind: expected a Transfer event") } fn decode_approval_event( event: &ink_env::test::EmittedEvent, ) -> (AccountId, AccountId, Balance) { let decoded_event = <Event as scale::Decode>::decode(&mut &event.data[..]) .expect("encountered invalid contract event data buffer"); if let Event::Approval(Approval { owner, spender, value, }) = decoded_event { return (owner, spender, value) } panic!("encountered unexpected event kind: expected a Transfer event") } fn assert_topics( event: &ink_env::test::EmittedEvent, expected_topics: &Vec<Hash>, ) { for (n, (actual_topic, expected_topic)) in event.topics.iter().zip(expected_topics).enumerate() { let topic = actual_topic .decode::<Hash>() .expect("encountered invalid topic encoding"); assert_eq!(topic, *expected_topic, "encountered invalid topic at {}", n); } } } impl Erc20 { #[ink(constructor)] pub fn new( name: String, symbol: String, decimals: u8, initial_supply: Balance, ) -> Self { let mut instance = Self { erc20: erc20::Data::new(), }; erc20::Impl::init(&mut instance, name, symbol, decimals, initial_supply); instance } #[ink(message)] pub fn name(&self) -> String { erc20::Impl::name(self) } #[ink(message)] pub fn symbol(&self) -> String { erc20::Impl::symbol(self) } #[ink(message)] pub fn decimals(&self) -> u8 { erc20::Impl::decimals(self) } #[ink(message)] pub fn total_supply(&self) -> Balance { erc20::Impl::total_supply(self) } #[ink(message)] pub fn balance_of(&self, owner: AccountId) -> Balance { erc20::Impl::balance_of(self, owner) } #[ink(message)] pub fn allowance(&self, owner: AccountId, spender: AccountId) -> Balance { erc20::Impl::allowance(self, owner, spender) } #[ink(message)] pub fn transfer(&mut self, to: AccountId, value: Balance) -> Result<()> { erc20::Impl::transfer(self, to, value) } #[ink(message)] pub fn approve(&mut self, spender: AccountId, value: Balance) -> Result<()> { erc20::Impl::approve(self, spender, value) } #[ink(message)] pub fn transfer_from( &mut self, from: AccountId, to: AccountId, value: Balance, ) -> Result<()> { erc20::Impl::transfer_from(self, from, to, value) } #[ink(message)] pub fn mint(&mut self, to: AccountId, value: Balance) -> Result<()> { erc20::Impl::_mint(self, to, value) } #[ink(message)] pub fn burn(&mut self, to: AccountId, value: Balance) -> Result<()> { erc20::Impl::_burn(self, to, value) } #[ink(message)] pub fn transfer_internal( &mut self, from: AccountId, to: AccountId, value: Balance, ) -> Result<()> { erc20::Impl::_transfer_from_to(self, from, to, value) } #[ink(message)] pub fn approve_internal( &mut self, owner: AccountId, spender: AccountId, value: Balance, ) -> Result<()> { erc20::Impl::_approve(self, owner, spender, value) } } }
#![cfg_attr(not(feature = "std"), no_std)] #[metis_lang::contract] pub mod erc20_contract { use super::super::behavior; pub use erc20::{ Error, Result, }; use metis_erc20 as erc20; use metis_lang::{ import, metis, }; #[ink(storage)] #[import(erc20)] pub struct Erc20 { erc20: erc20::Data<Erc20>, } #[cfg(not(feature = "ink-as-dependency"))] impl erc20::Impl<Erc20> for Erc20 {} type Event = <Erc20 as ink_lang::BaseEvent>::Type; #[ink(event)] #[metis(erc20)] pub struct Transfer { #[ink(topic)] pub from: Option<AccountId>, #[ink(topic)] pub to: Option<AccountId>, pub value: Balance, } #[ink(event)] #[metis(erc20)] pub struct Approval { #[ink(topic)] pub owner: AccountId, #[ink(topic)] pub spender: AccountId, pub value: Balance, } impl behavior::IERC20New<Erc20> for Erc20 { fn new_erc20( name: String, symbol: String, decimals: u8, initial_supply: Balance, ) -> Self { Self::new(name, symbol, decimals, initial_supply) } fn next_call_by(account: AccountId) { let callee = ink_env::account_id::<ink_env::DefaultEnvironment>() .unwrap_or([0x0; 32].into()); let mut data = ink_env::test::CallData::new(ink_env::call::Selector::new([0x00; 4])); data.push_arg(&account.clone()); ink_env::test::push_execution_context::<ink_env::DefaultEnvironment>( account.clone(), callee, 1000000, 1000000, data, ); } } impl behavior::IERC20Event<Erc20> for Erc20 { fn decode_transfer_event( event: &ink_env::test::EmittedEvent, ) -> (Option<AccountId>, Option<AccountId>, Balance) { let decoded_event = <Event as scale::Decode>::decode(&mut &event.data[..]) .expect("encountered invalid contract event data buffer"); if let Event::Transfer(Transfer { from, to, value }) = decoded_event { return (from, to, value) } panic!("encountered unexpected event kind: expected a Transfer event") } fn decode_approval_event( event: &ink_env::test::EmittedEvent, ) -> (AccountId, AccountId, Balance) { let decoded_event = <Event as scale::Decode>::decode(&mut &event.data[..]) .expect("encountered invalid contract event data buffer"); if let Event::Approval(Approval { owner, spender, value, }) = decoded_event { return (owner, spender, value) } panic!("encountered unexpected event kind: expected a Transfer event") } fn assert_topics( event: &ink_env::test::EmittedEvent, expected_topics: &Vec<Hash>, ) { for (n, (actual_topic, expected_topic)) in event.topics.iter().zip(expected_topics).enumerate() { let topic = actual_topic .decode::<Hash>() .expect("encountered invalid topic encoding"); assert_eq!(topic, *expected_topic, "encountered invalid topic at {}", n); } } } impl Erc20 { #[ink(constructor)] pub fn new( name: String, symbol: String, decimals: u8, initial_supply: Balance, ) -> Self { let mut instance = Self { erc20: erc20::Data::new(), }; erc20::Impl::init(&mut instance, name, symbol, decimals, initial_supply); instance } #[ink(message)] pub fn name(&self) -> String { erc20::Impl::name(self) } #[ink(message)] pub fn symbol(&self) -> String { erc20::Impl::symbol(self) } #[ink(message)] pub fn decimals(&self) -> u8 { erc20::Impl::decimals(self) } #[ink(message)] pub fn total_supply(&self) -> Balance { erc20::Impl::total_supply(self) } #[ink(message)] pub fn balance_of(&self, owner: AccountId) -> Balance { erc20::Impl::balance_of(self, owner) } #[ink(message)] pub fn allowance(&self, owner: AccountId, spender: AccountId) -> Balance { erc20::Impl::allowance(self, owner, spender) } #[ink(message)] pub fn transfer(&mut self, to: AccountId, value: Balance) -> Result<()> { erc20::Impl::transfer(self, to, value) } #[ink(message)] pub fn approve(&mut self, spender: AccountId, value: Balance) -> Result<()> { erc20::Impl::approve(self, spender, value) } #[ink(message)] pub fn transfer_from( &mut self, from: AccountId, to: AccountId, value: Balance, ) -> Result<()> { erc20::Impl::transfer_from(self, from, to, value) } #[ink(message)] pub fn mint(&mut self, to: AccountId, value: Balance) -> Result<()> { erc20::Impl::_mint(self, to, value) } #[ink(message)] pub fn burn(&mut self, to: AccountId, value: Balance) -> Result<()> { erc20::Impl::_burn(self, to, value) } #[ink(message)] pub fn transfer_internal( &mut self, from: AccountI
#[ink(message)] pub fn approve_internal( &mut self, owner: AccountId, spender: AccountId, value: Balance, ) -> Result<()> { erc20::Impl::_approve(self, owner, spender, value) } } }
d, to: AccountId, value: Balance, ) -> Result<()> { erc20::Impl::_transfer_from_to(self, from, to, value) }
function_block-function_prefixed
[ { "content": "fn get_storage_mod_type(contract: &Contract, ext_mod: &Ident) -> Result<TokenStream2> {\n\n let storage = contract.module().storage();\n\n let mod_to_get = Some(ext_mod.clone());\n\n\n\n for f in storage.fields() {\n\n if f.ident == mod_to_get {\n\n if let syn::Type::Pat...
Rust
src/pymodule/mod.rs
ripe-tech/pconvert-rust
cf9ffcfc59d5838cf4d74a2c6c666e3f94f7cdc3
pub mod conversions; pub mod utils; use crate::blending::params::{BlendAlgorithmParams, Options}; use crate::blending::{ blend_images, demultiply_image, get_blending_algorithm, is_algorithm_multiplied, BlendAlgorithm, }; use crate::constants; use crate::errors::PConvertError; use crate::parallelism::{ResultMessage, ThreadPool}; use crate::utils::{read_png_from_file, write_png_parallel, write_png_to_file}; use pyo3::exceptions::PyException; use pyo3::prelude::*; use pyo3::types::{IntoPyDict, PyDict, PySequence}; use std::sync::mpsc; use utils::{ build_algorithm, build_params, get_compression_type, get_filter_type, get_num_threads, }; static mut THREAD_POOL: Option<ThreadPool> = None; #[pymodule] fn pconvert_rust(_py: Python, module: &PyModule) -> PyResult<()> { unsafe { let mut thread_pool = ThreadPool::new(constants::DEFAULT_THREAD_POOL_SIZE).unwrap(); thread_pool.start(); THREAD_POOL = Some(thread_pool); } module.add("COMPILATION_DATE", constants::COMPILATION_DATE)?; module.add("COMPILATION_TIME", constants::COMPILATION_TIME)?; module.add("VERSION", constants::VERSION)?; module.add("ALGORITHMS", constants::ALGORITHMS.to_vec())?; module.add("COMPILER", constants::COMPILER)?; module.add("COMPILER_VERSION", constants::COMPILER_VERSION)?; module.add("LIBPNG_VERSION", constants::LIBPNG_VERSION)?; module.add("FEATURES", constants::FEATURES.to_vec())?; module.add("PLATFORM_CPU_BITS", constants::PLATFORM_CPU_BITS)?; let filters: Vec<String> = constants::FILTER_TYPES .to_vec() .iter() .map(|x| format!("{:?}", x)) .collect(); module.add("FILTER_TYPES", filters)?; let compressions: Vec<String> = constants::COMPRESSION_TYPES .to_vec() .iter() .map(|x| format!("{:?}", x)) .collect(); module.add("COMPRESSION_TYPES", compressions)?; #[pyfn(module, "blend_images")] fn blend_images_py( py: Python, bot_path: String, top_path: String, target_path: String, algorithm: Option<String>, is_inline: Option<bool>, options: Option<Options>, ) -> PyResult<()> { py.allow_threads(|| -> PyResult<()> { let num_threads = get_num_threads(&options); if num_threads <= 0 { blend_images_single_thread( bot_path, top_path, target_path, algorithm, is_inline, options, ) } else { unsafe { blend_images_multi_thread( bot_path, top_path, target_path, algorithm, is_inline, options, num_threads, ) } } }) } #[pyfn(module, "blend_multiple")] fn blend_multiple_py( py: Python, img_paths: &PySequence, out_path: String, algorithm: Option<String>, algorithms: Option<&PySequence>, is_inline: Option<bool>, options: Option<Options>, ) -> PyResult<()> { let img_paths: Vec<String> = img_paths.extract()?; let num_images = img_paths.len(); let algorithms_to_apply: Vec<(BlendAlgorithm, Option<BlendAlgorithmParams>)> = if let Some(algorithms) = algorithms { build_params(algorithms)? } else if let Some(algorithm) = algorithm { let algorithm = build_algorithm(&algorithm)?; vec![(algorithm, None); num_images - 1] } else { vec![(BlendAlgorithm::Multiplicative, None); num_images - 1] }; py.allow_threads(|| -> PyResult<()> { let num_threads = get_num_threads(&options); if num_threads <= 0 { blend_multiple_single_thread( img_paths, out_path, algorithms_to_apply, is_inline, options, ) } else { unsafe { blend_multiple_multi_thread( img_paths, out_path, algorithms_to_apply, is_inline, options, num_threads, ) } } }) } #[pyfn(module, "get_thread_pool_status")] fn get_thread_pool_status(py: Python) -> PyResult<&PyDict> { unsafe { match &mut THREAD_POOL { Some(thread_pool) => { let status_dict = thread_pool.get_status().into_py_dict(py); Ok(status_dict) } None => Err(PyException::new_err( "Acessing global thread pool".to_string(), )), } } } Ok(()) } fn blend_images_single_thread( bot_path: String, top_path: String, target_path: String, algorithm: Option<String>, is_inline: Option<bool>, options: Option<Options>, ) -> PyResult<()> { let algorithm = algorithm.unwrap_or_else(|| String::from("multiplicative")); let algorithm = build_algorithm(&algorithm)?; let _is_inline = is_inline.unwrap_or(false); let demultiply = is_algorithm_multiplied(&algorithm); let algorithm_fn = get_blending_algorithm(&algorithm); let mut bot = read_png_from_file(bot_path, demultiply)?; let top = read_png_from_file(top_path, demultiply)?; blend_images(&mut bot, &top, &algorithm_fn, &None); let compression_type = get_compression_type(&options); let filter_type = get_filter_type(&options); write_png_to_file(target_path, &bot, compression_type, filter_type)?; Ok(()) } unsafe fn blend_images_multi_thread( bot_path: String, top_path: String, target_path: String, algorithm: Option<String>, is_inline: Option<bool>, options: Option<Options>, num_threads: i32, ) -> PyResult<()> { let algorithm = algorithm.unwrap_or_else(|| String::from("multiplicative")); let algorithm = build_algorithm(&algorithm)?; let _is_inline = is_inline.unwrap_or(false); let demultiply = is_algorithm_multiplied(&algorithm); let algorithm_fn = get_blending_algorithm(&algorithm); let thread_pool = match &mut THREAD_POOL { Some(thread_pool) => thread_pool, None => panic!("Unable to access global pconvert thread pool"), }; thread_pool.expand_to(num_threads as usize); let bot_result_channel = thread_pool .execute(move || ResultMessage::ImageResult(read_png_from_file(bot_path, demultiply))); let top_result_channel = thread_pool .execute(move || ResultMessage::ImageResult(read_png_from_file(top_path, demultiply))); let mut bot = match bot_result_channel.recv().unwrap() { ResultMessage::ImageResult(result) => result, }?; let top = match top_result_channel.recv().unwrap() { ResultMessage::ImageResult(result) => result, }?; blend_images(&mut bot, &top, &algorithm_fn, &None); let compression_type = get_compression_type(&options); let filter_type = get_filter_type(&options); write_png_parallel(target_path, &bot, compression_type, filter_type)?; Ok(()) } fn blend_multiple_single_thread( img_paths: Vec<String>, out_path: String, algorithms: Vec<(BlendAlgorithm, Option<BlendAlgorithmParams>)>, is_inline: Option<bool>, options: Option<Options>, ) -> PyResult<()> { let num_images = img_paths.len(); if num_images < 1 { return Err(PyErr::from(PConvertError::ArgumentError( "ArgumentError: 'img_paths' must contain at least one path".to_string(), ))); } if algorithms.len() != num_images - 1 { return Err(PyErr::from(PConvertError::ArgumentError(format!( "ArgumentError: 'algorithms' must be of size {} (one per blending operation)", num_images - 1 )))); }; let _is_inline = is_inline.unwrap_or(false); let mut img_paths_iter = img_paths.iter(); let first_path = img_paths_iter.next().unwrap().to_string(); let first_demultiply = is_algorithm_multiplied(&algorithms[0].0); let mut composition = read_png_from_file(first_path, first_demultiply)?; let zip_iter = img_paths_iter.zip(algorithms.iter()); for pair in zip_iter { let path = pair.0.to_string(); let (algorithm, algorithm_params) = pair.1; let demultiply = is_algorithm_multiplied(&algorithm); let algorithm_fn = get_blending_algorithm(&algorithm); let current_layer = read_png_from_file(path, demultiply)?; blend_images( &mut composition, &current_layer, &algorithm_fn, algorithm_params, ); } let compression_type = get_compression_type(&options); let filter_type = get_filter_type(&options); write_png_to_file(out_path, &composition, compression_type, filter_type)?; Ok(()) } unsafe fn blend_multiple_multi_thread( img_paths: Vec<String>, out_path: String, algorithms: Vec<(BlendAlgorithm, Option<BlendAlgorithmParams>)>, is_inline: Option<bool>, options: Option<Options>, num_threads: i32, ) -> PyResult<()> { let num_images = img_paths.len(); if num_images < 1 { return Err(PyErr::from(PConvertError::ArgumentError( "ArgumentError: 'img_paths' must contain at least one path".to_string(), ))); } if algorithms.len() != num_images - 1 { return Err(PyErr::from(PConvertError::ArgumentError(format!( "ArgumentError: 'algorithms' must be of size {} (one per blending operation)", num_images - 1 )))); }; let _is_inline = is_inline.unwrap_or(false); let thread_pool = match &mut THREAD_POOL { Some(thread_pool) => thread_pool, None => panic!("Unable to access global pconvert thread pool"), }; thread_pool.expand_to(num_threads as usize); let mut png_channels: Vec<mpsc::Receiver<ResultMessage>> = Vec::with_capacity(num_images); for path in img_paths.into_iter() { let result_channel = thread_pool.execute(move || -> ResultMessage { ResultMessage::ImageResult(read_png_from_file(path, false)) }); png_channels.push(result_channel); } let first_demultiply = is_algorithm_multiplied(&algorithms[0].0); let mut composition = match png_channels[0].recv().unwrap() { ResultMessage::ImageResult(result) => result, }?; if first_demultiply { demultiply_image(&mut composition) } for i in 1..png_channels.len() { let (algorithm, algorithm_params) = &algorithms[i - 1]; let demultiply = is_algorithm_multiplied(&algorithm); let algorithm_fn = get_blending_algorithm(&algorithm); let mut current_layer = match png_channels[i].recv().unwrap() { ResultMessage::ImageResult(result) => result, }?; if demultiply { demultiply_image(&mut current_layer) } blend_images( &mut composition, &current_layer, &algorithm_fn, algorithm_params, ); } let compression_type = get_compression_type(&options); let filter_type = get_filter_type(&options); write_png_parallel(out_path, &composition, compression_type, filter_type)?; Ok(()) }
pub mod conversions; pub mod utils; use crate::blending::params::{BlendAlgorithmParams, Options}; use crate::blending::{ blend_images, demultiply_image, get_blending_algorithm, is_algorithm_multiplied, BlendAlgorithm, }; use crate::constants; use crate::errors::PConvertError; use crate::parallelism::{ResultMessage, ThreadPool}; use crate::utils::{read_png_from_file, write_png_parallel, write_png_to_file}; use pyo3::exceptions::PyException; use pyo3::prelude::*; use pyo3::types::{IntoPyDict, PyDict, PySequence}; use std::sync::mpsc; use utils::{ build_algorithm, build_params, get_compression_type, get_filter_type, get_num_threads, }; static mut THREAD_POOL: Option<ThreadPool> = None; #[pymodule] fn pconvert_rust(_py: Python, module: &PyModule) -> PyResult<()> { unsafe { let mut thread_pool = ThreadPool::new(constants::DEFAULT_THREAD_POOL_SIZE).unwrap(); thread_pool.start(); THREAD_POOL = Some(thread_pool); } module.add("COMPILATION_DATE", constants::COMPILATION_DATE)?; module.add("COMPILATION_TIME", constants::COMPILATION_TIME)?; module.add("VERSION", constants::VERSION)?; module.add("ALGORITHMS", constants::ALGORITHMS.to_vec())?; module.add("COMPILER", constants::COMPILER)?; module.add("COMPILER_VERSION", constants::COMPILER_VERSION)?; module.add("LIBPNG_VERSION", constants::LIBPNG_VERSION)?; module.add("FEATURES", constants::FEATURES.to_vec())?; module.add("PLATFORM_CPU_BITS", constants::PLATFORM_CPU_BITS)?; let filters: Vec<String> = constants::FILTER_TYPES .to_vec() .iter() .map(|x| format!("{:?}", x)) .collect(); module.add("FILTER_TYPES", filters)?; let compressions: Vec<String> = constants::COMPRESSION_TYPES .to_vec() .iter() .map(|x| format!("{:?}", x)) .collect(); module.add("COMPRESSION_TYPES", compressions)?; #[pyfn(module, "blend_images")] fn blend_images_py( py: Python, bot_path: String, top_path: String, target_path: String, algorithm: Option<String>, is_inline: Option<bool>, options: Option<Options>, ) -> PyResult<()> { py.allow_threads(|| -> PyResult<()> { let num_threads = get_num_threads(&options); if num_threads <= 0 { blend_images_single_thread( bot_path, top_path, target_path, algorithm, is_inline, options, ) } else { unsafe { blend_images_multi_thread( bot_path, top_path, target_path, algorithm, is_inline, options, num_threads, ) } } }) } #[pyfn(module, "blend_multiple")] fn blend_multiple_py( py: Python, img_paths: &PySequence, out_path: String, algorithm: Option<String>, algorithms: Option<&PySequence>, is_inline: Option<bool>, options: Option<Options>, ) -> PyResult<()> { let img_paths: Vec<String> = img_paths.extract()?; let num_images =
#[pyfn(module, "get_thread_pool_status")] fn get_thread_pool_status(py: Python) -> PyResult<&PyDict> { unsafe { match &mut THREAD_POOL { Some(thread_pool) => { let status_dict = thread_pool.get_status().into_py_dict(py); Ok(status_dict) } None => Err(PyException::new_err( "Acessing global thread pool".to_string(), )), } } } Ok(()) } fn blend_images_single_thread( bot_path: String, top_path: String, target_path: String, algorithm: Option<String>, is_inline: Option<bool>, options: Option<Options>, ) -> PyResult<()> { let algorithm = algorithm.unwrap_or_else(|| String::from("multiplicative")); let algorithm = build_algorithm(&algorithm)?; let _is_inline = is_inline.unwrap_or(false); let demultiply = is_algorithm_multiplied(&algorithm); let algorithm_fn = get_blending_algorithm(&algorithm); let mut bot = read_png_from_file(bot_path, demultiply)?; let top = read_png_from_file(top_path, demultiply)?; blend_images(&mut bot, &top, &algorithm_fn, &None); let compression_type = get_compression_type(&options); let filter_type = get_filter_type(&options); write_png_to_file(target_path, &bot, compression_type, filter_type)?; Ok(()) } unsafe fn blend_images_multi_thread( bot_path: String, top_path: String, target_path: String, algorithm: Option<String>, is_inline: Option<bool>, options: Option<Options>, num_threads: i32, ) -> PyResult<()> { let algorithm = algorithm.unwrap_or_else(|| String::from("multiplicative")); let algorithm = build_algorithm(&algorithm)?; let _is_inline = is_inline.unwrap_or(false); let demultiply = is_algorithm_multiplied(&algorithm); let algorithm_fn = get_blending_algorithm(&algorithm); let thread_pool = match &mut THREAD_POOL { Some(thread_pool) => thread_pool, None => panic!("Unable to access global pconvert thread pool"), }; thread_pool.expand_to(num_threads as usize); let bot_result_channel = thread_pool .execute(move || ResultMessage::ImageResult(read_png_from_file(bot_path, demultiply))); let top_result_channel = thread_pool .execute(move || ResultMessage::ImageResult(read_png_from_file(top_path, demultiply))); let mut bot = match bot_result_channel.recv().unwrap() { ResultMessage::ImageResult(result) => result, }?; let top = match top_result_channel.recv().unwrap() { ResultMessage::ImageResult(result) => result, }?; blend_images(&mut bot, &top, &algorithm_fn, &None); let compression_type = get_compression_type(&options); let filter_type = get_filter_type(&options); write_png_parallel(target_path, &bot, compression_type, filter_type)?; Ok(()) } fn blend_multiple_single_thread( img_paths: Vec<String>, out_path: String, algorithms: Vec<(BlendAlgorithm, Option<BlendAlgorithmParams>)>, is_inline: Option<bool>, options: Option<Options>, ) -> PyResult<()> { let num_images = img_paths.len(); if num_images < 1 { return Err(PyErr::from(PConvertError::ArgumentError( "ArgumentError: 'img_paths' must contain at least one path".to_string(), ))); } if algorithms.len() != num_images - 1 { return Err(PyErr::from(PConvertError::ArgumentError(format!( "ArgumentError: 'algorithms' must be of size {} (one per blending operation)", num_images - 1 )))); }; let _is_inline = is_inline.unwrap_or(false); let mut img_paths_iter = img_paths.iter(); let first_path = img_paths_iter.next().unwrap().to_string(); let first_demultiply = is_algorithm_multiplied(&algorithms[0].0); let mut composition = read_png_from_file(first_path, first_demultiply)?; let zip_iter = img_paths_iter.zip(algorithms.iter()); for pair in zip_iter { let path = pair.0.to_string(); let (algorithm, algorithm_params) = pair.1; let demultiply = is_algorithm_multiplied(&algorithm); let algorithm_fn = get_blending_algorithm(&algorithm); let current_layer = read_png_from_file(path, demultiply)?; blend_images( &mut composition, &current_layer, &algorithm_fn, algorithm_params, ); } let compression_type = get_compression_type(&options); let filter_type = get_filter_type(&options); write_png_to_file(out_path, &composition, compression_type, filter_type)?; Ok(()) } unsafe fn blend_multiple_multi_thread( img_paths: Vec<String>, out_path: String, algorithms: Vec<(BlendAlgorithm, Option<BlendAlgorithmParams>)>, is_inline: Option<bool>, options: Option<Options>, num_threads: i32, ) -> PyResult<()> { let num_images = img_paths.len(); if num_images < 1 { return Err(PyErr::from(PConvertError::ArgumentError( "ArgumentError: 'img_paths' must contain at least one path".to_string(), ))); } if algorithms.len() != num_images - 1 { return Err(PyErr::from(PConvertError::ArgumentError(format!( "ArgumentError: 'algorithms' must be of size {} (one per blending operation)", num_images - 1 )))); }; let _is_inline = is_inline.unwrap_or(false); let thread_pool = match &mut THREAD_POOL { Some(thread_pool) => thread_pool, None => panic!("Unable to access global pconvert thread pool"), }; thread_pool.expand_to(num_threads as usize); let mut png_channels: Vec<mpsc::Receiver<ResultMessage>> = Vec::with_capacity(num_images); for path in img_paths.into_iter() { let result_channel = thread_pool.execute(move || -> ResultMessage { ResultMessage::ImageResult(read_png_from_file(path, false)) }); png_channels.push(result_channel); } let first_demultiply = is_algorithm_multiplied(&algorithms[0].0); let mut composition = match png_channels[0].recv().unwrap() { ResultMessage::ImageResult(result) => result, }?; if first_demultiply { demultiply_image(&mut composition) } for i in 1..png_channels.len() { let (algorithm, algorithm_params) = &algorithms[i - 1]; let demultiply = is_algorithm_multiplied(&algorithm); let algorithm_fn = get_blending_algorithm(&algorithm); let mut current_layer = match png_channels[i].recv().unwrap() { ResultMessage::ImageResult(result) => result, }?; if demultiply { demultiply_image(&mut current_layer) } blend_images( &mut composition, &current_layer, &algorithm_fn, algorithm_params, ); } let compression_type = get_compression_type(&options); let filter_type = get_filter_type(&options); write_png_parallel(out_path, &composition, compression_type, filter_type)?; Ok(()) }
img_paths.len(); let algorithms_to_apply: Vec<(BlendAlgorithm, Option<BlendAlgorithmParams>)> = if let Some(algorithms) = algorithms { build_params(algorithms)? } else if let Some(algorithm) = algorithm { let algorithm = build_algorithm(&algorithm)?; vec![(algorithm, None); num_images - 1] } else { vec![(BlendAlgorithm::Multiplicative, None); num_images - 1] }; py.allow_threads(|| -> PyResult<()> { let num_threads = get_num_threads(&options); if num_threads <= 0 { blend_multiple_single_thread( img_paths, out_path, algorithms_to_apply, is_inline, options, ) } else { unsafe { blend_multiple_multi_thread( img_paths, out_path, algorithms_to_apply, is_inline, options, num_threads, ) } } }) }
function_block-function_prefixed
[ { "content": "/// Attempts to parse a `&String` to a `BlendAlgorithm`.\n\n/// Returns the enum variant if it succeeds. Otherwise it returns a `PyErr`.\n\npub fn build_algorithm(algorithm: &str) -> Result<BlendAlgorithm, PyErr> {\n\n match BlendAlgorithm::from_str(algorithm) {\n\n Ok(algorithm) => Ok(a...
Rust
src/lib.rs
estchd/passable_guard
0549276b278e11e75c6e8f0b65a689d2eab812e2
use std::marker::PhantomData; use std::ffi::CString; #[derive(Debug, Clone)] pub enum ReconstituteError<PTR, PAS: Passable<PTR>> { PointerMismatch{passed: *mut PTR, reconstituted: *mut PTR}, ReconstituteError{error: PAS::ReconstituteError} } #[derive(Debug, Clone)] pub struct PassableContainer<PTR, PAS: Passable<PTR>> { value: PAS, _phantom: PhantomData<PTR> } impl<PTR, PAS: Passable<PTR>> PassableContainer<PTR, PAS> { pub fn new(passable: PAS) -> Self { Self { value: passable, _phantom: Default::default() } } pub fn into_inner(self) -> PAS { self.value } pub fn pass(self) -> (PassableGuard<PTR, PAS>, *mut PTR) { let ptr = self.value.pass(); let guard = PassableGuard { ptr, _phantom: Default::default() }; (guard, ptr) } pub unsafe fn pass_unguarded(self) -> *mut PTR { self.value.pass() } } #[derive(Debug, Clone)] pub struct PassableGuard<PTR, PAS: Passable<PTR>> { ptr: *mut PTR, _phantom: PhantomData<PAS> } impl<PTR, PAS: Passable<PTR>> PassableGuard<PTR, PAS> { pub unsafe fn reconstitute(self, ptr: *mut PTR) -> Result<PassableContainer<PTR, PAS>, ReconstituteError<PTR, PAS>> { if self.ptr != ptr { return Err( ReconstituteError::PointerMismatch { passed: self.ptr, reconstituted: ptr } ); } PAS::reconstitute(ptr) .map(|passable| PassableContainer::new(passable)) .map_err( |err| ReconstituteError::ReconstituteError {error: err} ) } } impl<PTR, PAS: Passable<PTR>> Drop for PassableGuard<PTR, PAS> { fn drop(&mut self) { panic!("Passable Guard dropped before being reconstituted"); } } pub trait Passable<PTR> : Sized { type ReconstituteError; fn pass(self) -> *mut PTR; unsafe fn reconstitute(ptr: *mut PTR) -> Result<Self, Self::ReconstituteError>; } impl Passable<u8> for CString { type ReconstituteError = (); fn pass(self) -> *mut u8 { self.into_raw() as *mut u8 } unsafe fn reconstitute(ptr: *mut u8) -> Result<Self, Self::ReconstituteError> { Ok(CString::from_raw(ptr as *mut i8)) } }
use std::marker::PhantomData; use std::ffi::CString; #[derive(Debug, Clone)] pub enum ReconstituteError<PTR, PAS: Passable<PTR>> { PointerMismatch{passed: *mut PTR, reconstituted: *mut PTR}, ReconstituteError{error: PAS::ReconstituteError} } #[derive(Debug, Clone)] pub struct PassableContainer<PTR, PAS: Passable<PTR>> { value: PAS, _phantom: PhantomData<PTR> } impl<PTR, PAS: Passable<PTR>> PassableContainer<PTR, PAS> { pub fn new(passable: PAS) -> Self { Self { value: passable, _phantom: Default::default() } } pub fn into_inner(self) -> PAS { self.value } pub fn pass(self) -> (PassableGuard<PTR, PAS>, *mut PTR) { let ptr = self.value.pass(); let guard = PassableGuard { ptr, _phantom: Default::default() }; (guard, ptr) } pub unsafe fn pass_unguarded(self) -> *mut PTR { self.value.pass() } } #[derive(Debug, Clone)] pub struct PassableGuard<PTR, PAS: Passable<PTR>> { ptr: *mut PTR, _phantom: PhantomData<PAS> } impl<PTR, PAS: Passable<PTR>> PassableGuard<PTR, PAS> { pub unsafe fn reconstitute(self, ptr: *mut PTR) -> Result<PassableContainer<PTR, PAS>, ReconstituteError<PTR, PAS>> { if self.ptr != ptr { return
; } PAS::reconstitute(ptr) .map(|passable| PassableContainer::new(passable)) .map_err( |err| ReconstituteError::ReconstituteError {error: err} ) } } impl<PTR, PAS: Passable<PTR>> Drop for PassableGuard<PTR, PAS> { fn drop(&mut self) { panic!("Passable Guard dropped before being reconstituted"); } } pub trait Passable<PTR> : Sized { type ReconstituteError; fn pass(self) -> *mut PTR; unsafe fn reconstitute(ptr: *mut PTR) -> Result<Self, Self::ReconstituteError>; } impl Passable<u8> for CString { type ReconstituteError = (); fn pass(self) -> *mut u8 { self.into_raw() as *mut u8 } unsafe fn reconstitute(ptr: *mut u8) -> Result<Self, Self::ReconstituteError> { Ok(CString::from_raw(ptr as *mut i8)) } }
Err( ReconstituteError::PointerMismatch { passed: self.ptr, reconstituted: ptr } )
call_expression
[ { "content": "# Passable Guard\n\n\n\nThe Passable Guard Crate provides a way to check for FFI memory leaks at runtime.\n\n\n\nThis is achieved by providing a PassableContainer class that encapsulates\n\na Passable Object that can be converted to a raw pointer to pass it over a FFI boundary.\n\n\n\nThis Passabl...
Rust
liblumen_core/src/sys/unix/dynamic_call.rs
mlwilkerson/lumen
048df6c0840c11496e2d15aa9af2e4a8d07a6e0f
use crate::sys::dynamic_call::DynamicCallee; extern "C" { #[unwind(allowed)] #[link_name = "__lumen_dynamic_apply"] pub fn apply(f: DynamicCallee, argv: *const usize, argc: usize) -> usize; } #[cfg(all(target_os = "macos", target_arch = "x86_64"))] global_asm!(include_str!("dynamic_call/lumen_dynamic_apply_macos.s")); #[cfg(all(target_os = "linux", target_arch = "x86_64"))] global_asm!(include_str!("dynamic_call/lumen_dynamic_apply_linux.s")); #[cfg(test)] mod tests { use super::*; use core::mem; #[test] fn basic_apply_test() { let callee = adder as *const (); let callee = unsafe { mem::transmute::<*const (), DynamicCallee>(callee) }; let args = &[22, 11]; let argv = args.as_ptr(); let argc = args.len(); let result = unsafe { apply(callee, argv, argc) }; assert_eq!(result, 33); } #[test] fn basic_apply_rustcc_test() { let callee = adder_rust as *const (); let callee = unsafe { mem::transmute::<*const (), DynamicCallee>(callee) }; let args = &[22, 11]; let argv = args.as_ptr(); let argc = args.len(); let result = unsafe { apply(callee, argv, argc) }; assert_eq!(result, 33); } #[test] fn spilled_args_even_spills_apply_test() { let callee = spilled_args_even as *const (); let callee = unsafe { mem::transmute::<*const (), DynamicCallee>(callee) }; let args = &[1, 1, 1, 1, 1, 1, 1, 1, 1]; let argv = args.as_ptr(); let argc = args.len(); let result = unsafe { apply(callee, argv, argc) }; assert_eq!(result, 8); } #[test] fn spilled_args_odd_spills_apply_test() { let callee = spilled_args_odd as *const (); let callee = unsafe { mem::transmute::<*const (), DynamicCallee>(callee) }; let args = &[1, 1, 1, 1, 1, 1, 1, 1]; let argv = args.as_ptr(); let argc = args.len(); let result = unsafe { apply(callee, argv, argc) }; assert_eq!(result, 7); } #[test] #[should_panic] fn panic_apply_test() { let callee = panicky as *const (); let callee = unsafe { mem::transmute::<*const (), DynamicCallee>(callee) }; let args = &[22, 11]; let argv = args.as_ptr(); let argc = args.len(); let _result = unsafe { apply(callee, argv, argc) }; } #[test] #[should_panic] fn panic_apply_spills_test() { let callee = panicky_spilled as *const (); let callee = unsafe { mem::transmute::<*const (), DynamicCallee>(callee) }; let args = &[1, 1, 1, 1, 1, 1, 1, 1]; let argv = args.as_ptr(); let argc = args.len(); let _result = unsafe { apply(callee, argv, argc) }; } fn panicky(_x: usize, _y: usize) -> usize { panic!("panicky"); } #[unwind(allowed)] extern "C" fn panicky_spilled( _a: usize, _b: usize, _c: usize, _d: usize, _e: usize, _f: usize, _g: usize, ) -> usize { panic!("panicky"); } extern "C" fn adder(x: usize, y: usize) -> usize { x + y } fn adder_rust(x: usize, y: usize) -> usize { x + y } extern "C" fn spilled_args_even( a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, g: usize, h: usize, ) -> usize { a + b + c + d + e + f + g + h } extern "C" fn spilled_args_odd( a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, g: usize, ) -> usize { a + b + c + d + e + f + g } }
use crate::sys::dynamic_call::DynamicCallee; extern "C" { #[unwind(allowed)] #[link_name = "__lumen_dynamic_apply"] pub fn apply(f: DynamicCallee, argv: *const usize, argc: usize) -> usize; } #[cfg(all(target_os = "macos", target_arch = "x86_64"))] global_asm!(include_str!("dynamic_call/lumen_dynamic_apply_macos.s")); #[cfg(all(target_os = "linux", target_arch = "x86_64"))] global_asm!(include_str!("dynamic_call/lumen_dynamic_apply_linux.s")); #[cfg(test)] mod tests { use super::*; use core::mem; #[test] fn basic_apply_test() { let callee = adder as *const (); let callee = unsafe { mem::transmute::<*const (), DynamicCallee>(callee) }; let args = &[22, 11]; let argv = args.as_ptr(); let argc = args.len(); let result = unsafe { apply(callee, argv, argc) }; assert_eq!(result, 33); } #[test] fn basic_apply_rustcc_test() { let callee = adder_rust as *const (); let callee = unsafe { mem::transmute::<*const (), DynamicCallee>(callee) }; let args = &[22, 11]; let argv = args.as_ptr(); let argc = args.len(); let result = unsafe { apply(callee, argv, argc) }; assert_eq!(result, 33); } #[test] fn spilled_args_even_spills_apply_test() { let callee = spilled_args_even as *const (); let callee = unsafe { mem::transmute::<*const (), DynamicCallee>(callee) }; let args = &[1, 1, 1, 1, 1, 1, 1, 1, 1]; let argv = args.as_ptr(); let argc = args.len(); let result = unsafe { apply(callee, argv, argc) }; assert_eq!(result, 8); } #[test] fn spilled_args_odd_spills_apply_test() { let callee = spilled_args_odd as *const (); let callee = unsafe { mem::transmute::<*const (), DynamicCallee>(callee) }; let args = &[1, 1, 1, 1, 1, 1, 1, 1]; let argv = args.as_ptr(); let argc = args.len(); let result = unsafe { apply(callee, argv, argc) }; assert_eq!(result, 7); } #[test] #[should_panic] fn panic_apply_test() { let callee = panicky as *const (); let callee = unsafe { mem::transmute::<*const (), DynamicCallee>(callee) }; let args = &[22, 11]; let argv = args.as_ptr(); let argc = args.len(); let _result = unsafe { apply(callee, argv, argc) }; } #[test] #[should_panic] fn panic_apply_spills_test() { let callee = panicky_spilled as *const (); let callee = unsafe { mem::transmute::<*const (), DynamicCallee>(callee) }; let args = &[1, 1, 1, 1, 1, 1, 1, 1]; let argv = args.as_ptr(); let argc = args.len(); let _result = unsafe { apply(callee, argv, argc) }; } fn panicky(_x: usize, _y: usize) -> usize { panic!("panicky"); } #[unwind(allowed)] extern "C" fn panicky_spilled( _a: usize, _b: usize, _c: usize, _d: usize, _e: usize, _f: usize, _g: usize, ) -> usize { panic!("panicky"); } extern "C" fn adder(x: usize, y: usize) -> usize { x + y } fn adder_rust(x: usize, y: usize) -> usize { x + y }
extern "C" fn spilled_args_odd( a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, g: usize, ) -> usize { a + b + c + d + e + f + g } }
extern "C" fn spilled_args_even( a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, g: usize, h: usize, ) -> usize { a + b + c + d + e + f + g + h }
function_block-full_function
[ { "content": "/// Invoke the statically linked `lld` linker with the given arguments.\n\n///\n\n/// NOTE: Assumes that the first value of the argument vector contains the\n\n/// program name which informs lld which flavor of linker is being run.\n\npub fn link(argv: &[CString]) -> Result<(), ()> {\n\n // Acq...
Rust
ipp-util/src/util.rs
simlay/ipp-sys
3b894faf6eb0533663c2d83fea0c9e851ac2d188
use std::{ffi::OsString, io, path::PathBuf}; use futures::{future, Future}; use structopt::StructOpt; use tokio::io::AsyncRead; use ipp_client::{IppClient, IppClientBuilder, IppError}; use ipp_proto::ipp::DelimiterTag; use ipp_proto::{IppAttribute, IppOperationBuilder, IppValue}; fn new_client(uri: &str, params: &IppParams) -> IppClient { IppClientBuilder::new(&uri) .timeout(params.timeout) .ca_certs(&params.ca_certs) .verify_hostname(!params.no_verify_hostname) .verify_certificate(!params.no_verify_certificate) .build() } struct JobSource { inner: Box<dyn AsyncRead + Send>, } fn new_source(cmd: &IppPrintCmd) -> Box<dyn Future<Item = JobSource, Error = io::Error> + Send + 'static> { match cmd.file { Some(ref filename) => Box::new( tokio::fs::File::open(filename.to_owned()).and_then(|file| Ok(JobSource { inner: Box::new(file) })), ), None => Box::new(future::ok(JobSource { inner: Box::new(tokio::io::stdin()), })), } } fn do_print(params: &IppParams, cmd: IppPrintCmd) -> Result<(), IppError> { let mut runtime = tokio::runtime::Runtime::new().unwrap(); let client = new_client(&cmd.uri, params); if !cmd.no_check_state { runtime.block_on(client.check_ready())?; } runtime.block_on(new_source(&cmd).map_err(IppError::from).and_then(move |source| { let mut builder = IppOperationBuilder::print_job(source.inner); if let Some(jobname) = cmd.job_name { builder = builder.job_title(&jobname); } if let Some(username) = cmd.user_name { builder = builder.user_name(&username); } for arg in cmd.options { let mut kv = arg.split('='); if let Some(k) = kv.next() { if let Some(v) = kv.next() { let value = if let Ok(iv) = v.parse::<i32>() { IppValue::Integer(iv) } else if v == "true" || v == "false" { IppValue::Boolean(v == "true") } else { IppValue::Keyword(v.to_string()) }; builder = builder.attribute(IppAttribute::new(k, value)); } } } client.send(builder.build()).and_then(|attrs| { if let Some(group) = attrs.groups_of(DelimiterTag::JobAttributes).get(0) { for v in group.attributes().values() { println!("{}: {}", v.name(), v.value()); } } Ok(()) }) })) } fn do_status(params: &IppParams, cmd: IppStatusCmd) -> Result<(), IppError> { let client = new_client(&cmd.uri, &params); let operation = IppOperationBuilder::get_printer_attributes() .attributes(&cmd.attributes) .build(); let mut runtime = tokio::runtime::Runtime::new().unwrap(); let attrs = runtime.block_on(client.send(operation))?; if let Some(group) = attrs.groups_of(DelimiterTag::PrinterAttributes).get(0) { let mut values: Vec<_> = group.attributes().values().collect(); values.sort_by(|a, b| a.name().cmp(b.name())); for v in values { println!("{}: {}", v.name(), v.value()); } } Ok(()) } #[derive(StructOpt)] #[structopt(name = "IPP print utility", about = "", author = "", rename_all = "kebab-case")] struct IppParams { #[structopt( long = "ca-cert", short = "c", global = true, help = "Additional CA root certificates in PEM or DER format" )] ca_certs: Vec<String>, #[structopt( long = "no-verify-hostname", global = true, help = "Disable TLS host name verification (insecure!)" )] no_verify_hostname: bool, #[structopt( long = "no-verify-certificate", global = true, help = "Disable TLS certificate verification (insecure!)" )] no_verify_certificate: bool, #[structopt( default_value = "0", long = "timeout", short = "t", global = true, help = "IPP request timeout in seconds, 0 = no timeout" )] timeout: u64, #[structopt(subcommand)] command: IppCommand, } #[derive(StructOpt)] enum IppCommand { #[structopt(name = "print", about = "Print file to an IPP printer", author = "")] Print(IppPrintCmd), #[structopt(name = "status", about = "Get status of an IPP printer", author = "")] Status(IppStatusCmd), } #[derive(StructOpt, Clone)] #[structopt(name = "IPP print utility", about = "", author = "", rename_all = "kebab-case")] struct IppPrintCmd { #[structopt(help = "Printer URI")] uri: String, #[structopt( long = "no-check-state", short = "n", help = "Do not check printer state before printing" )] no_check_state: bool, #[structopt( long = "file", short = "f", help = "Input file name to print [default: standard input]" )] file: Option<PathBuf>, #[structopt(long = "job-name", short = "j", help = "Job name to send as job-name attribute")] job_name: Option<String>, #[structopt( long = "user-name", short = "u", help = "User name to send as requesting-user-name attribute" )] user_name: Option<String>, #[structopt(long = "option", short = "o", help = "Extra IPP job attributes in key=value format")] options: Vec<String>, } #[derive(StructOpt, Clone)] #[structopt(name = "IPP print utility", about = "", author = "", rename_all = "kebab-case")] struct IppStatusCmd { #[structopt(help = "Printer URI")] uri: String, #[structopt(long = "attribute", short = "a", help = "Attributes to query, default is to get all")] attributes: Vec<String>, } pub fn ipp_main<I, T>(args: I) -> Result<(), IppError> where I: IntoIterator<Item = T>, T: Into<OsString> + Clone, { let params = IppParams::from_iter_safe(args).map_err(|e| IppError::ParamError(e.to_string()))?; match params.command { IppCommand::Status(ref cmd) => do_status(&params, cmd.clone())?, IppCommand::Print(ref cmd) => do_print(&params, cmd.clone())?, } Ok(()) }
use std::{ffi::OsString, io, path::PathBuf}; use futures::{future, Future}; use structopt::StructOpt; use tokio::io::AsyncRead; use ipp_client::{IppClient, IppClientBuilder, IppError}; use ipp_proto::ipp::DelimiterTag; use ipp_proto::{IppAttribute, IppOperationBuilder, IppValue}; fn new_client(uri: &str, params: &IppParams) -> IppClient { IppClientBuilder::new(&uri) .timeout(params.timeou
struct JobSource { inner: Box<dyn AsyncRead + Send>, } fn new_source(cmd: &IppPrintCmd) -> Box<dyn Future<Item = JobSource, Error = io::Error> + Send + 'static> { match cmd.file { Some(ref filename) => Box::new( tokio::fs::File::open(filename.to_owned()).and_then(|file| Ok(JobSource { inner: Box::new(file) })), ), None => Box::new(future::ok(JobSource { inner: Box::new(tokio::io::stdin()), })), } } fn do_print(params: &IppParams, cmd: IppPrintCmd) -> Result<(), IppError> { let mut runtime = tokio::runtime::Runtime::new().unwrap(); let client = new_client(&cmd.uri, params); if !cmd.no_check_state { runtime.block_on(client.check_ready())?; } runtime.block_on(new_source(&cmd).map_err(IppError::from).and_then(move |source| { let mut builder = IppOperationBuilder::print_job(source.inner); if let Some(jobname) = cmd.job_name { builder = builder.job_title(&jobname); } if let Some(username) = cmd.user_name { builder = builder.user_name(&username); } for arg in cmd.options { let mut kv = arg.split('='); if let Some(k) = kv.next() { if let Some(v) = kv.next() { let value = if let Ok(iv) = v.parse::<i32>() { IppValue::Integer(iv) } else if v == "true" || v == "false" { IppValue::Boolean(v == "true") } else { IppValue::Keyword(v.to_string()) }; builder = builder.attribute(IppAttribute::new(k, value)); } } } client.send(builder.build()).and_then(|attrs| { if let Some(group) = attrs.groups_of(DelimiterTag::JobAttributes).get(0) { for v in group.attributes().values() { println!("{}: {}", v.name(), v.value()); } } Ok(()) }) })) } fn do_status(params: &IppParams, cmd: IppStatusCmd) -> Result<(), IppError> { let client = new_client(&cmd.uri, &params); let operation = IppOperationBuilder::get_printer_attributes() .attributes(&cmd.attributes) .build(); let mut runtime = tokio::runtime::Runtime::new().unwrap(); let attrs = runtime.block_on(client.send(operation))?; if let Some(group) = attrs.groups_of(DelimiterTag::PrinterAttributes).get(0) { let mut values: Vec<_> = group.attributes().values().collect(); values.sort_by(|a, b| a.name().cmp(b.name())); for v in values { println!("{}: {}", v.name(), v.value()); } } Ok(()) } #[derive(StructOpt)] #[structopt(name = "IPP print utility", about = "", author = "", rename_all = "kebab-case")] struct IppParams { #[structopt( long = "ca-cert", short = "c", global = true, help = "Additional CA root certificates in PEM or DER format" )] ca_certs: Vec<String>, #[structopt( long = "no-verify-hostname", global = true, help = "Disable TLS host name verification (insecure!)" )] no_verify_hostname: bool, #[structopt( long = "no-verify-certificate", global = true, help = "Disable TLS certificate verification (insecure!)" )] no_verify_certificate: bool, #[structopt( default_value = "0", long = "timeout", short = "t", global = true, help = "IPP request timeout in seconds, 0 = no timeout" )] timeout: u64, #[structopt(subcommand)] command: IppCommand, } #[derive(StructOpt)] enum IppCommand { #[structopt(name = "print", about = "Print file to an IPP printer", author = "")] Print(IppPrintCmd), #[structopt(name = "status", about = "Get status of an IPP printer", author = "")] Status(IppStatusCmd), } #[derive(StructOpt, Clone)] #[structopt(name = "IPP print utility", about = "", author = "", rename_all = "kebab-case")] struct IppPrintCmd { #[structopt(help = "Printer URI")] uri: String, #[structopt( long = "no-check-state", short = "n", help = "Do not check printer state before printing" )] no_check_state: bool, #[structopt( long = "file", short = "f", help = "Input file name to print [default: standard input]" )] file: Option<PathBuf>, #[structopt(long = "job-name", short = "j", help = "Job name to send as job-name attribute")] job_name: Option<String>, #[structopt( long = "user-name", short = "u", help = "User name to send as requesting-user-name attribute" )] user_name: Option<String>, #[structopt(long = "option", short = "o", help = "Extra IPP job attributes in key=value format")] options: Vec<String>, } #[derive(StructOpt, Clone)] #[structopt(name = "IPP print utility", about = "", author = "", rename_all = "kebab-case")] struct IppStatusCmd { #[structopt(help = "Printer URI")] uri: String, #[structopt(long = "attribute", short = "a", help = "Attributes to query, default is to get all")] attributes: Vec<String>, } pub fn ipp_main<I, T>(args: I) -> Result<(), IppError> where I: IntoIterator<Item = T>, T: Into<OsString> + Clone, { let params = IppParams::from_iter_safe(args).map_err(|e| IppError::ParamError(e.to_string()))?; match params.command { IppCommand::Status(ref cmd) => do_status(&params, cmd.clone())?, IppCommand::Print(ref cmd) => do_print(&params, cmd.clone())?, } Ok(()) }
t) .ca_certs(&params.ca_certs) .verify_hostname(!params.no_verify_hostname) .verify_certificate(!params.no_verify_certificate) .build() }
function_block-function_prefixed
[ { "content": "fn to_device_uri(uri: &str) -> Cow<str> {\n\n match Url::parse(&uri) {\n\n Ok(ref mut url) if !url.username().is_empty() => {\n\n let _ = url.set_username(\"\");\n\n let _ = url.set_password(None);\n\n Cow::Owned(url.to_string())\n\n }\n\n _...
Rust
ovium/src/server.rs
snoir/ovium
357723ee3eb78b46c11ed4ce4b2b6c8e5fedb383
use crate::error::{ConfigError, Error, ErrorKind, OviumError}; use crate::types::*; use crossbeam_channel::unbounded; use crossbeam_utils::thread; use log::{error, info}; use serde::Deserialize; use signal_hook::{iterator::Signals, SIGINT}; use ssh2::Session; use std::collections::HashMap; use std::fs::File; use std::io::prelude::*; use std::io::{self, BufRead, BufReader}; use std::net::TcpStream; use std::os::unix::net::{UnixListener, UnixStream}; use std::path::Path; use std::time::Duration; pub struct Server<'a> { socket_path: &'a str, config: ServerConfig, listener: UnixListener, } #[derive(Deserialize, Debug)] pub struct ServerConfig { pub nodes: HashMap<String, Node>, #[serde(default)] pub groups: HashMap<String, Vec<String>>, } impl ServerConfig { pub fn is_group(&self, name: &str) -> bool { self.groups.contains_key(name) } } impl Server<'_> { pub fn new<'a>(socket_path: &'a str, config_path: &'a str) -> Result<Server<'a>, OviumError> { let server_config = ServerConfig::new(Path::new(config_path))?; let listener = UnixListener::bind(socket_path).map_err(|err| (ErrorKind::Bind, err.into()))?; listener .set_nonblocking(true) .map_err(|err| (ErrorKind::Bind, err.into()))?; Ok(Server { socket_path, config: server_config, listener, }) } pub fn run(&self) -> Result<(), OviumError> { thread::scope(|s| -> Result<(), OviumError> { let (signal_sender, signal_receiver) = unbounded(); let signals = Signals::new(&[SIGINT]).unwrap(); s.spawn(move |_| { for sig in signals.forever() { println!("Received signal {:?}", sig); if sig == signal_hook::SIGINT { signal_sender.clone().send(sig).unwrap(); break; } } }); for stream in self.listener.incoming() { if signal_receiver.clone().try_recv().is_ok() { break; } match stream { Ok(stream) => { /* connection succeeded */ let stream_receiver = signal_receiver.clone(); s.spawn::<_, Result<(), OviumError>>(move |_| { self.handle_client(stream, stream_receiver) .map_err(|err| (ErrorKind::Handle, err))?; Ok(()) }); } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { std::thread::sleep(Duration::from_millis(500)); continue; } Err(_) => { /* connection failed */ break; } } } Ok(()) }) .unwrap()?; Ok(()) } fn handle_client( &self, stream: UnixStream, _signal_receiver: crossbeam_channel::Receiver<i32>, ) -> Result<(), Error> { let mut reader = BufReader::new(&stream); loop { let mut resp = Vec::new(); let read_bytes = reader.read_until(b'\n', &mut resp); match read_bytes { Ok(read_bytes) => { if read_bytes == 0 { info!("connection closed by remote"); } else { let recv_request = Request::decode(&resp)?; let handler = match recv_request { Request::Cmd(inner_req) => { ServerHandler::<CmdRequest>::new(stream, inner_req) } }; handler.validate_request(&self.config)?; handler.handle(&self.config)?; }; break; } Err(err) => match err.kind() { io::ErrorKind::Interrupted => continue, _ => break, }, } } Ok(()) } pub fn execute_cmd(node: &Node, cmd: String) -> Result<SshSuccess, Error> { let node_addr = format!("{}:{}", node.ip, node.port); let tcp = TcpStream::connect(node_addr)?; let mut sess = Session::new()?; sess.set_tcp_stream(tcp); sess.handshake()?; sess.userauth_agent(&node.user)?; let mut channel = sess.channel_session()?; channel.exec(&cmd)?; let mut stdout_string = String::new(); let mut stderr_string = String::new(); channel.read_to_string(&mut stdout_string)?; channel.stderr().read_to_string(&mut stderr_string)?; channel.wait_close()?; let stdout_string = stdout_string.replace("\n", "\\n"); let stderr_string = stderr_string.replace("\n", "\\n"); let stderr = if stderr_string.is_empty() { None } else { Some(stderr_string) }; let stdout = if stdout_string.is_empty() { None } else { Some(stdout_string) }; let exit_status = channel.exit_status()?; Ok(SshSuccess { stdout, stderr, exit_status, }) } } impl Drop for Server<'_> { fn drop(&mut self) { std::fs::remove_file(&self.socket_path).unwrap(); } } impl ServerConfig { pub fn new(config_dir: &Path) -> Result<ServerConfig, OviumError> { let nodes_file_path = config_dir.join("nodes.toml"); let nodes_config_string = match read_file(&nodes_file_path) { Ok(config_string) => config_string, Err(err) => { error!("Unable to load file {:?}: {}", &nodes_file_path, err); return Err(OviumError::from((ErrorKind::LoadConfig, err))); } }; let config: ServerConfig = toml::from_str(&nodes_config_string) .map_err(|err| (ErrorKind::InvalidConfig, ConfigError::Parse(err).into()))?; validate_config(&config).map_err(|err| (ErrorKind::InvalidConfig, err.into()))?; Ok(config) } } fn validate_config(config: &ServerConfig) -> Result<(), ConfigError> { let mut unknown_nodes: Vec<String> = Vec::new(); for node_group in &config.groups { for node in node_group.1 { if !config.nodes.contains_key(node) { unknown_nodes.push(node.to_string()); } } } if !unknown_nodes.is_empty() { return Err(ConfigError::UnknownNodes(unknown_nodes)); } Ok(()) } fn read_file(file: &Path) -> Result<String, Error> { let mut f = File::open(file)?; let mut file_string = String::new(); f.read_to_string(&mut file_string)?; Ok(file_string) }
use crate::error::{ConfigError, Error, ErrorKind, OviumError}; use crate::types::*; use crossbeam_channel::unbounded; use crossbeam_utils::thread; use log::{error, info}; use serde::Deserialize; use signal_hook::{iterator::Signals, SIGINT}; use ssh2::Session; use std::collections::HashMap; use std::fs::File; use std::io::prelude::*; use std::io::{self, BufRead, BufReader}; use std::net::TcpStream; use std::os::unix::net::{UnixListener, UnixStream}; use std::path::Path; use std::time::Duration; pub struct Server<'a> { socket_path: &'a str, config: ServerConfig, listener: UnixListener, } #[derive(Deserialize, Debug)] pub struct ServerConfig { pub nodes: HashMap<String, Node>, #[serde(default)] pub groups: HashMap<String, Vec<String>>, } impl ServerConfig { pub fn is_group(&self, name: &str) -> bool { self.groups.contains_key(name) } } impl Server<'_> { pub fn new<'a>(socket_path: &'a str, config_path: &'a str) -> Result<Server<'a>, OviumError> { let server_config = ServerConfig::new(Path::new(config_path))?; let listener = UnixListener::bind(socket_path).map_err(|err| (ErrorKind::Bind, err.into()))?; listener .set_nonblocking(true) .map_err(|err| (ErrorKind::Bind, err.into()))?; Ok(Server { socket_path, config: server_config, listener, }) } pub fn run(&self) -> Result<(), OviumError> { thread::scope(|s| -> Result<(), OviumError> { let (signal_sender, signal_receiver) = unbounded(); let signals = Signals::new(&[SIGINT]).unwrap(); s.spawn(move |_| { for sig in signals.forever() { println!("Received signal {:?}", sig); if sig == signal_hook::SIGINT { signal_sender.clone().send(sig).unwrap(); break; } } }); for stream in self.listener.incoming() { if signal_receiver.clone().try_recv().is_ok() { break; } match stream { Ok(stream) => { /* connection succeeded */ let stream_receiver = signal_receiver.clone(); s.spawn::<_, Result<(), OviumError>>(move |_| { self.handle_client(stream, stream_receiver) .map_err(|err| (ErrorKind::Handle, err))?; Ok(()) }); } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { std::thread::sleep(Duration::from_millis(500)); continue; } Err(_) => { /* connection failed */ break; } } } Ok(()) }) .unwrap()?; Ok(()) }
pub fn execute_cmd(node: &Node, cmd: String) -> Result<SshSuccess, Error> { let node_addr = format!("{}:{}", node.ip, node.port); let tcp = TcpStream::connect(node_addr)?; let mut sess = Session::new()?; sess.set_tcp_stream(tcp); sess.handshake()?; sess.userauth_agent(&node.user)?; let mut channel = sess.channel_session()?; channel.exec(&cmd)?; let mut stdout_string = String::new(); let mut stderr_string = String::new(); channel.read_to_string(&mut stdout_string)?; channel.stderr().read_to_string(&mut stderr_string)?; channel.wait_close()?; let stdout_string = stdout_string.replace("\n", "\\n"); let stderr_string = stderr_string.replace("\n", "\\n"); let stderr = if stderr_string.is_empty() { None } else { Some(stderr_string) }; let stdout = if stdout_string.is_empty() { None } else { Some(stdout_string) }; let exit_status = channel.exit_status()?; Ok(SshSuccess { stdout, stderr, exit_status, }) } } impl Drop for Server<'_> { fn drop(&mut self) { std::fs::remove_file(&self.socket_path).unwrap(); } } impl ServerConfig { pub fn new(config_dir: &Path) -> Result<ServerConfig, OviumError> { let nodes_file_path = config_dir.join("nodes.toml"); let nodes_config_string = match read_file(&nodes_file_path) { Ok(config_string) => config_string, Err(err) => { error!("Unable to load file {:?}: {}", &nodes_file_path, err); return Err(OviumError::from((ErrorKind::LoadConfig, err))); } }; let config: ServerConfig = toml::from_str(&nodes_config_string) .map_err(|err| (ErrorKind::InvalidConfig, ConfigError::Parse(err).into()))?; validate_config(&config).map_err(|err| (ErrorKind::InvalidConfig, err.into()))?; Ok(config) } } fn validate_config(config: &ServerConfig) -> Result<(), ConfigError> { let mut unknown_nodes: Vec<String> = Vec::new(); for node_group in &config.groups { for node in node_group.1 { if !config.nodes.contains_key(node) { unknown_nodes.push(node.to_string()); } } } if !unknown_nodes.is_empty() { return Err(ConfigError::UnknownNodes(unknown_nodes)); } Ok(()) } fn read_file(file: &Path) -> Result<String, Error> { let mut f = File::open(file)?; let mut file_string = String::new(); f.read_to_string(&mut file_string)?; Ok(file_string) }
fn handle_client( &self, stream: UnixStream, _signal_receiver: crossbeam_channel::Receiver<i32>, ) -> Result<(), Error> { let mut reader = BufReader::new(&stream); loop { let mut resp = Vec::new(); let read_bytes = reader.read_until(b'\n', &mut resp); match read_bytes { Ok(read_bytes) => { if read_bytes == 0 { info!("connection closed by remote"); } else { let recv_request = Request::decode(&resp)?; let handler = match recv_request { Request::Cmd(inner_req) => { ServerHandler::<CmdRequest>::new(stream, inner_req) } }; handler.validate_request(&self.config)?; handler.handle(&self.config)?; }; break; } Err(err) => match err.kind() { io::ErrorKind::Interrupted => continue, _ => break, }, } } Ok(()) }
function_block-full_function
[ { "content": "#[proc_macro_derive(FromParsedResource)]\n\npub fn from_parsed_resource(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n let fields_name = match input.data {\n\n Data::Struct(data_struct) => {\n\n let mut fields = Vec::new()...
Rust
tough/tests/target_path_safety.rs
flavio/tough
0ebe90c54d1b993d64c265a2d315cad3ad9a1699
mod test_utils; use chrono::{DateTime, TimeZone, Utc}; use maplit::hashmap; use ring::rand::SystemRandom; use std::collections::HashMap; use std::fs::{self, create_dir_all, File}; use std::num::NonZeroU64; use std::path::Path; use tempfile::TempDir; use test_utils::{dir_url, test_data, DATA_1, DATA_2, DATA_3}; use tough::editor::signed::SignedRole; use tough::editor::RepositoryEditor; use tough::key_source::{KeySource, LocalKeySource}; use tough::schema::{KeyHolder, PathPattern, PathSet, RoleKeys, RoleType, Root, Signed, Target}; use tough::{Prefix, RepositoryLoader, TargetName}; fn later() -> DateTime<Utc> { Utc.ymd(2999, 1, 1).and_hms(0, 0, 0) } fn create_root(root_path: &Path, consistent_snapshot: bool) -> Vec<Box<dyn KeySource>> { let keys: Vec<Box<dyn KeySource>> = vec![Box::new(LocalKeySource { path: test_data().join("snakeoil.pem"), })]; let key_pair = keys.iter().next().unwrap().as_sign().unwrap().tuf_key(); let key_id = key_pair.key_id().unwrap(); let empty_keys = RoleKeys { keyids: vec![key_id.clone()], threshold: NonZeroU64::new(1).unwrap(), _extra: Default::default(), }; let mut root = Signed { signed: Root { spec_version: "1.0.0".into(), consistent_snapshot, version: NonZeroU64::new(1).unwrap(), expires: later(), keys: HashMap::new(), roles: hashmap! { RoleType::Root => empty_keys.clone(), RoleType::Snapshot => empty_keys.clone(), RoleType::Targets => empty_keys.clone(), RoleType::Timestamp => empty_keys.clone(), }, _extra: HashMap::new(), }, signatures: Vec::new(), }; root.signed.keys.insert(key_id.clone(), key_pair.clone()); let signed_root = SignedRole::new( root.signed.clone(), &KeyHolder::Root(root.signed.clone()), &keys, &SystemRandom::new(), ) .unwrap(); std::fs::write(&root_path, signed_root.buffer()).unwrap(); keys } #[test] fn safe_target_paths() { let tempdir = TempDir::new().unwrap(); let root_path = tempdir.path().join("root.json"); let keys = create_root(&root_path, false); let one = NonZeroU64::new(1).unwrap(); let mut editor = RepositoryEditor::new(&root_path).unwrap(); editor .snapshot_version(one) .snapshot_expires(later()) .timestamp_version(one) .timestamp_expires(later()) .delegate_role( "delegated", &keys, PathSet::Paths(vec![PathPattern::new("delegated/*").unwrap()]), one, later(), one, ) .unwrap(); let repo_dir = tempdir.path().join("repo"); let targets_dir = repo_dir.join("targets"); fs::create_dir_all(targets_dir.join("foo/bar")).unwrap(); fs::create_dir_all(targets_dir.join("delegated/subdir")).unwrap(); let targets_file_1 = targets_dir.join("data1.txt"); let targets_file_2 = targets_dir.join("foo/bar/data2.txt"); let targets_file_3 = targets_dir.join("delegated/subdir/data3.txt"); fs::write(&targets_file_1, DATA_1).unwrap(); fs::write(&targets_file_2, DATA_2).unwrap(); fs::write(&targets_file_3, DATA_3).unwrap(); let target_name_1 = TargetName::new("foo/../bar/../baz/../../../../data1.txt").unwrap(); let target_1 = Target::from_path(&targets_file_1).unwrap(); let target_name_2 = TargetName::new("foo/bar/baz/../data2.txt").unwrap(); let target_2 = Target::from_path(&targets_file_2).unwrap(); let target_name_3 = TargetName::new("../delegated/foo/../subdir/data3.txt").unwrap(); let target_3 = Target::from_path(&targets_file_3).unwrap(); editor.add_target(target_name_1.clone(), target_1).unwrap(); editor.add_target(target_name_2.clone(), target_2).unwrap(); editor .targets_version(one) .unwrap() .targets_expires(later()) .unwrap() .sign_targets_editor(&keys) .unwrap() .change_delegated_targets("delegated") .unwrap() .add_target(target_name_3.clone(), target_3) .unwrap() .targets_version(one) .unwrap() .targets_expires(later()) .unwrap() .sign_targets_editor(&keys) .unwrap(); let signed_repo = editor.sign(&keys).unwrap(); let metadata_dir = repo_dir.join("metadata"); signed_repo.write(&metadata_dir).unwrap(); let loaded_repo = RepositoryLoader::new( File::open(&root_path).unwrap(), dir_url(&metadata_dir), dir_url(&targets_dir), ) .load() .unwrap(); let outdir = tempdir.path().join("outdir"); create_dir_all(&outdir).unwrap(); loaded_repo .save_target(&target_name_1, &outdir, Prefix::None) .unwrap(); loaded_repo .save_target(&target_name_2, &outdir, Prefix::None) .unwrap(); loaded_repo .save_target(&target_name_3, &outdir, Prefix::None) .unwrap(); assert!(!outdir.join("bar").exists()); assert!(!outdir.join("baz").exists()); assert!(!outdir.join("foo/bar/baz").exists()); assert!(!outdir.join("../delegated/foo/../subdir/data3.txt").exists()); assert_eq!( fs::read_to_string(outdir.join("data1.txt")).unwrap(), DATA_1 ); assert_eq!( fs::read_to_string(outdir.join("foo/bar/data2.txt")).unwrap(), DATA_2 ); assert_eq!( fs::read_to_string(outdir.join("delegated/subdir/data3.txt")).unwrap(), DATA_3 ); }
mod test_utils; use chrono::{DateTime, TimeZone, Utc}; use maplit::hashmap; use ring::rand::SystemRandom; use std::collections::HashMap; use std::fs::{self, create_dir_all, File}; use std::num::NonZeroU64; use std::path::Path; use tempfile
ap(); editor.add_target(target_name_2.clone(), target_2).unwrap(); editor .targets_version(one) .unwrap() .targets_expires(later()) .unwrap() .sign_targets_editor(&keys) .unwrap() .change_delegated_targets("delegated") .unwrap() .add_target(target_name_3.clone(), target_3) .unwrap() .targets_version(one) .unwrap() .targets_expires(later()) .unwrap() .sign_targets_editor(&keys) .unwrap(); let signed_repo = editor.sign(&keys).unwrap(); let metadata_dir = repo_dir.join("metadata"); signed_repo.write(&metadata_dir).unwrap(); let loaded_repo = RepositoryLoader::new( File::open(&root_path).unwrap(), dir_url(&metadata_dir), dir_url(&targets_dir), ) .load() .unwrap(); let outdir = tempdir.path().join("outdir"); create_dir_all(&outdir).unwrap(); loaded_repo .save_target(&target_name_1, &outdir, Prefix::None) .unwrap(); loaded_repo .save_target(&target_name_2, &outdir, Prefix::None) .unwrap(); loaded_repo .save_target(&target_name_3, &outdir, Prefix::None) .unwrap(); assert!(!outdir.join("bar").exists()); assert!(!outdir.join("baz").exists()); assert!(!outdir.join("foo/bar/baz").exists()); assert!(!outdir.join("../delegated/foo/../subdir/data3.txt").exists()); assert_eq!( fs::read_to_string(outdir.join("data1.txt")).unwrap(), DATA_1 ); assert_eq!( fs::read_to_string(outdir.join("foo/bar/data2.txt")).unwrap(), DATA_2 ); assert_eq!( fs::read_to_string(outdir.join("delegated/subdir/data3.txt")).unwrap(), DATA_3 ); }
::TempDir; use test_utils::{dir_url, test_data, DATA_1, DATA_2, DATA_3}; use tough::editor::signed::SignedRole; use tough::editor::RepositoryEditor; use tough::key_source::{KeySource, LocalKeySource}; use tough::schema::{KeyHolder, PathPattern, PathSet, RoleKeys, RoleType, Root, Signed, Target}; use tough::{Prefix, RepositoryLoader, TargetName}; fn later() -> DateTime<Utc> { Utc.ymd(2999, 1, 1).and_hms(0, 0, 0) } fn create_root(root_path: &Path, consistent_snapshot: bool) -> Vec<Box<dyn KeySource>> { let keys: Vec<Box<dyn KeySource>> = vec![Box::new(LocalKeySource { path: test_data().join("snakeoil.pem"), })]; let key_pair = keys.iter().next().unwrap().as_sign().unwrap().tuf_key(); let key_id = key_pair.key_id().unwrap(); let empty_keys = RoleKeys { keyids: vec![key_id.clone()], threshold: NonZeroU64::new(1).unwrap(), _extra: Default::default(), }; let mut root = Signed { signed: Root { spec_version: "1.0.0".into(), consistent_snapshot, version: NonZeroU64::new(1).unwrap(), expires: later(), keys: HashMap::new(), roles: hashmap! { RoleType::Root => empty_keys.clone(), RoleType::Snapshot => empty_keys.clone(), RoleType::Targets => empty_keys.clone(), RoleType::Timestamp => empty_keys.clone(), }, _extra: HashMap::new(), }, signatures: Vec::new(), }; root.signed.keys.insert(key_id.clone(), key_pair.clone()); let signed_root = SignedRole::new( root.signed.clone(), &KeyHolder::Root(root.signed.clone()), &keys, &SystemRandom::new(), ) .unwrap(); std::fs::write(&root_path, signed_root.buffer()).unwrap(); keys } #[test] fn safe_target_paths() { let tempdir = TempDir::new().unwrap(); let root_path = tempdir.path().join("root.json"); let keys = create_root(&root_path, false); let one = NonZeroU64::new(1).unwrap(); let mut editor = RepositoryEditor::new(&root_path).unwrap(); editor .snapshot_version(one) .snapshot_expires(later()) .timestamp_version(one) .timestamp_expires(later()) .delegate_role( "delegated", &keys, PathSet::Paths(vec![PathPattern::new("delegated/*").unwrap()]), one, later(), one, ) .unwrap(); let repo_dir = tempdir.path().join("repo"); let targets_dir = repo_dir.join("targets"); fs::create_dir_all(targets_dir.join("foo/bar")).unwrap(); fs::create_dir_all(targets_dir.join("delegated/subdir")).unwrap(); let targets_file_1 = targets_dir.join("data1.txt"); let targets_file_2 = targets_dir.join("foo/bar/data2.txt"); let targets_file_3 = targets_dir.join("delegated/subdir/data3.txt"); fs::write(&targets_file_1, DATA_1).unwrap(); fs::write(&targets_file_2, DATA_2).unwrap(); fs::write(&targets_file_3, DATA_3).unwrap(); let target_name_1 = TargetName::new("foo/../bar/../baz/../../../../data1.txt").unwrap(); let target_1 = Target::from_path(&targets_file_1).unwrap(); let target_name_2 = TargetName::new("foo/bar/baz/../data2.txt").unwrap(); let target_2 = Target::from_path(&targets_file_2).unwrap(); let target_name_3 = TargetName::new("../delegated/foo/../subdir/data3.txt").unwrap(); let target_3 = Target::from_path(&targets_file_3).unwrap(); editor.add_target(target_name_1.clone(), target_1).unwr
random
[ { "content": "fn round_time(time: DateTime<Utc>) -> DateTime<Utc> {\n\n // `Timelike::with_nanosecond` returns None only when passed a value >= 2_000_000_000\n\n time.with_nanosecond(0).unwrap()\n\n}\n\n\n", "file_path": "tuftool/src/root.rs", "rank": 0, "score": 81033.12215003767 }, { ...
Rust
src/core/value.rs
aesedepece/scriptful
37f6ff8361077ac63ab861273ba75b4f0571706d
#[derive(Clone, Debug, PartialOrd)] pub enum Value { Boolean(bool), Float(f64), Integer(i128), String(&'static str), } impl core::ops::Not for Value { type Output = Self; fn not(self) -> Self::Output { use Value::*; match self { Boolean(x) => Boolean(!x), Float(x) => Float(-x), Integer(x) => Integer(-x), _ => panic!("Type of {:?} cannot be negated", self), } } } #[allow(clippy::suspicious_arithmetic_impl)] impl core::ops::Add for Value { type Output = Self; fn add(self, rhs: Self) -> Self::Output { use Value::*; match (self, rhs) { (Boolean(a), Boolean(b)) => Boolean(a || b), (Float(a), Float(b)) => Float(a + b), (Float(a), Integer(b)) => Float(a + b as f64), (Integer(a), Integer(b)) => Integer(a + b), (Integer(a), Float(b)) => Float(a as f64 + b), (a, b) => panic!("Types of {:?} and {:?} cannot be added together", a, b), } } } #[allow(clippy::suspicious_arithmetic_impl)] impl core::ops::Mul for Value { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { use Value::*; match (self, rhs) { (Boolean(a), Boolean(b)) => Boolean(a && b), (Float(a), Float(b)) => Float(a * b), (Float(a), Integer(b)) => Float(a * b as f64), (Integer(a), Integer(b)) => Integer(a * b), (Integer(a), Float(b)) => Float(a as f64 * b), (a, b) => panic!("Types of {:?} and {:?} cannot be multiplied together", a, b), } } } impl core::ops::Sub for Value { type Output = Self; fn sub(self, rhs: Self) -> Self::Output { self + !rhs } } impl core::cmp::PartialEq for Value { fn eq(&self, other: &Self) -> bool { use Value::*; match (self, other) { (Boolean(a), Boolean(b)) => a == b, (Float(a), Float(b)) => (a - b) * (a - b) < 0.000_000_000_000_000_000_1, (Float(a), Integer(b)) => { (a - *b as f64) * (a - *b as f64) < 0.000_000_000_000_000_000_1 } (Integer(a), Integer(b)) => a == b, (Integer(a), Float(b)) => { (*a as f64 - b) * (*a as f64 - *b) < 0.000_000_000_000_000_000_1 } (String(a), String(b)) => a == b, _ => false, } } } #[cfg(test)] mod tests { use crate::core::value::Value::*; #[test] fn test_negation() { assert_eq!(!Boolean(true), Boolean(false)); assert_eq!(!Boolean(false), Boolean(true)); assert_eq!(!Float(0.), Float(0.)); assert_eq!(!Float(1.1), Float(-1.1)); assert_eq!(!Integer(0), Integer(0)); assert_eq!(!Integer(1), Integer(-1)); } #[test] fn test_addition() { assert_eq!(Boolean(false) + Boolean(false), Boolean(false)); assert_eq!(Boolean(false) + Boolean(true), Boolean(true)); assert_eq!(Boolean(true) + Boolean(false), Boolean(true)); assert_eq!(Boolean(true) + Boolean(true), Boolean(true)); assert_eq!(Float(1.1) + Float(2.2), Float(3.3)); assert_eq!(Float(1.1) + Float(-2.2), Float(-1.1)); assert_eq!(Float(1.1) + Integer(2), Float(3.1)); assert_eq!(Float(1.1) + Integer(-2), Float(-0.9)); assert_eq!(Integer(1) + Integer(2), Integer(3)); assert_eq!(Integer(1) + Integer(-2), Integer(-1)); assert_eq!(Integer(1) + Float(2.2), Float(3.2)); assert_eq!(Integer(1) + Float(-2.1), Float(-1.1)); } #[test] fn test_subtraction() { assert_eq!(Boolean(false) - Boolean(false), Boolean(true)); assert_eq!(Boolean(false) - Boolean(true), Boolean(false)); assert_eq!(Boolean(true) - Boolean(false), Boolean(true)); assert_eq!(Boolean(true) - Boolean(true), Boolean(true)); assert_eq!(Float(1.1) - Float(2.2), Float(-1.1)); assert_eq!(Float(1.1) - Float(-2.2), Float(3.3)); assert_eq!(Float(1.1) - Integer(2), Float(-0.9)); assert_eq!(Float(1.1) - Integer(-2), Float(3.1)); assert_eq!(Integer(1) - Integer(2), Integer(-1)); assert_eq!(Integer(1) - Integer(-2), Integer(3)); assert_eq!(Integer(1) - Float(2.2), Float(-1.2)); assert_eq!(Integer(1) - Float(-2.2), Float(3.2)); } #[test] fn test_multiplication() { assert_eq!(Boolean(false) * Boolean(false), Boolean(false)); assert_eq!(Boolean(false) * Boolean(true), Boolean(false)); assert_eq!(Boolean(true) * Boolean(false), Boolean(false)); assert_eq!(Boolean(true) * Boolean(true), Boolean(true)); assert_eq!(Float(1.1) * Float(2.2), Float(2.42)); assert_eq!(Float(1.1) * Float(-2.2), Float(-2.42)); assert_eq!(Float(1.1) * Integer(2), Float(2.2)); assert_eq!(Float(1.1) * Integer(-2), Float(-2.2)); assert_eq!(Integer(1) * Integer(2), Integer(2)); assert_eq!(Integer(1) * Integer(-2), Integer(-2)); assert_eq!(Integer(1) * Float(2.2), Float(2.2)); assert_eq!(Integer(1) * Float(-2.2), Float(-2.2)); } #[test] fn test_comparison() { assert_eq!(Boolean(false) == Boolean(false), true); assert_eq!(Boolean(false) == Boolean(true), false); assert_eq!(Boolean(true) == Boolean(false), false); assert_eq!(Boolean(true) == Boolean(true), true); assert_eq!(Float(1.1) == Float(1.1), true); assert_eq!(Float(1.1) == Float(2.2), false); assert_eq!(Float(-1.1) == Float(-1.1), true); assert_eq!(Float(-1.1) == Float(-2.2), false); assert_eq!(Float(1.1) == Float(-1.1), false); assert_eq!(Float(1.) == Integer(1), true); assert_eq!(Float(-1.) == Integer(-1), true); assert_eq!(Integer(1) == Integer(1), true); assert_eq!(Integer(1) == Integer(2), false); assert_eq!(Integer(-1) == Integer(-1), true); assert_eq!(Integer(-1) == Integer(-2), false); assert_eq!(Integer(1) == Integer(-1), false); assert_eq!(Integer(1) == Float(1.), true); assert_eq!(Integer(-1) == Float(-1.), true); } }
#[derive(Clone, Debug, PartialOrd)] pub enum Value { Boolean(bool), Float(f64), Integer(i128), String(&'static str), } impl core::ops::Not for Value { type Output = Self; fn not(self) -> Self::Output { use Value::*; match self { Boolean(x) => Boolean(!x), Float(x) => Float(-x), Integer(x) => Integer(-x), _ => panic!("Type of {:?} cannot be negated", self), } } } #[allow(clippy::suspicious_arithmetic_impl)] impl core::ops::Add for Value { type Output = Self; fn add(self, rhs: Self) -> Self::Output { use Value::*; match (self, rhs) { (Boolean(a), Boolean(b)) => Boolean(a || b), (Float(a), Float(b)) => Float(a + b), (Float(a), Integer(b)) => Float(a + b as f64), (Integer(a), Integer(b)) => Integer(a + b), (Integer(a), Float(b)) => Float(a as f64 + b), (a, b) => panic!("Types of {:?} and {:?} cannot be added together", a, b), } } } #[allow(clippy::suspicious_arithmetic_impl)] impl core::ops::Mul for Value { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { use Value::*; match (self, rhs) { (Boolean(a), Boolean(b)) => Boolean(a && b), (Float(a), Float(b)) => Float(a * b), (Float(a), Integer(b)) => Float(a * b as f64), (Integer(a), Integer(b)) => Integer(a * b), (Integer(a), Float(b)) => Float(a as f64 * b), (a, b) => panic!("Types of {:?} and {:?} cannot be multiplied together", a, b), } } } impl core::ops::Sub for Value { type Output = Self; fn sub(self, rhs: Self) -> Self::Output { self + !rhs } } impl core::cmp::PartialEq for Value { fn eq(&self, other: &Self) -> bool { use Value::*; match (self, other) { (Boolean(a), Boolean(b)) => a == b, (Float(a), Float(b)) => (a - b) * (a - b) < 0.000_000_000_000_000_000_1, (Float(a), Integer(b)) => { (a - *b as f64) * (a - *b as f64) < 0.000_000_000_000_000_000_1 } (Integer(a), Integer(b)) => a == b, (Integer(a), Float(b)) => { (*a as f64 - b) * (*a as f64 - *b) < 0.000_000_000_000_000_000_1 } (String(a), String(b)) => a == b, _ => false, } } } #[cfg(test)] mod tests { use crate::core::value::Value::*; #[test] fn test_negation() { assert_eq!(!Boolean(true), Boolean(false)); assert_eq!(!Boolean(false), Boolean(true)); assert_eq!(!Float(0.), Float(0.)); assert_eq!(!Float(1.1), Float(-1.1)); assert_eq!(!Integer(0), Integer(0)); assert_eq!(!Integer(1), Integer(-1)); } #[test] fn test_addition() { assert_eq!(Boolean(false) + Boolean(false), Boolean(false)); assert_eq!(Boolean(false) + Boolean(true), Boolean(true)); assert_eq!(Boolean(true) + Boolea
at(2.2), Float(3.3)); assert_eq!(Float(1.1) + Float(-2.2), Float(-1.1)); assert_eq!(Float(1.1) + Integer(2), Float(3.1)); assert_eq!(Float(1.1) + Integer(-2), Float(-0.9)); assert_eq!(Integer(1) + Integer(2), Integer(3)); assert_eq!(Integer(1) + Integer(-2), Integer(-1)); assert_eq!(Integer(1) + Float(2.2), Float(3.2)); assert_eq!(Integer(1) + Float(-2.1), Float(-1.1)); } #[test] fn test_subtraction() { assert_eq!(Boolean(false) - Boolean(false), Boolean(true)); assert_eq!(Boolean(false) - Boolean(true), Boolean(false)); assert_eq!(Boolean(true) - Boolean(false), Boolean(true)); assert_eq!(Boolean(true) - Boolean(true), Boolean(true)); assert_eq!(Float(1.1) - Float(2.2), Float(-1.1)); assert_eq!(Float(1.1) - Float(-2.2), Float(3.3)); assert_eq!(Float(1.1) - Integer(2), Float(-0.9)); assert_eq!(Float(1.1) - Integer(-2), Float(3.1)); assert_eq!(Integer(1) - Integer(2), Integer(-1)); assert_eq!(Integer(1) - Integer(-2), Integer(3)); assert_eq!(Integer(1) - Float(2.2), Float(-1.2)); assert_eq!(Integer(1) - Float(-2.2), Float(3.2)); } #[test] fn test_multiplication() { assert_eq!(Boolean(false) * Boolean(false), Boolean(false)); assert_eq!(Boolean(false) * Boolean(true), Boolean(false)); assert_eq!(Boolean(true) * Boolean(false), Boolean(false)); assert_eq!(Boolean(true) * Boolean(true), Boolean(true)); assert_eq!(Float(1.1) * Float(2.2), Float(2.42)); assert_eq!(Float(1.1) * Float(-2.2), Float(-2.42)); assert_eq!(Float(1.1) * Integer(2), Float(2.2)); assert_eq!(Float(1.1) * Integer(-2), Float(-2.2)); assert_eq!(Integer(1) * Integer(2), Integer(2)); assert_eq!(Integer(1) * Integer(-2), Integer(-2)); assert_eq!(Integer(1) * Float(2.2), Float(2.2)); assert_eq!(Integer(1) * Float(-2.2), Float(-2.2)); } #[test] fn test_comparison() { assert_eq!(Boolean(false) == Boolean(false), true); assert_eq!(Boolean(false) == Boolean(true), false); assert_eq!(Boolean(true) == Boolean(false), false); assert_eq!(Boolean(true) == Boolean(true), true); assert_eq!(Float(1.1) == Float(1.1), true); assert_eq!(Float(1.1) == Float(2.2), false); assert_eq!(Float(-1.1) == Float(-1.1), true); assert_eq!(Float(-1.1) == Float(-2.2), false); assert_eq!(Float(1.1) == Float(-1.1), false); assert_eq!(Float(1.) == Integer(1), true); assert_eq!(Float(-1.) == Integer(-1), true); assert_eq!(Integer(1) == Integer(1), true); assert_eq!(Integer(1) == Integer(2), false); assert_eq!(Integer(-1) == Integer(-1), true); assert_eq!(Integer(-1) == Integer(-2), false); assert_eq!(Integer(1) == Integer(-1), false); assert_eq!(Integer(1) == Float(1.), true); assert_eq!(Integer(-1) == Float(-1.), true); } }
n(false), Boolean(true)); assert_eq!(Boolean(true) + Boolean(true), Boolean(true)); assert_eq!(Float(1.1) + Flo
function_block-random_span
[ { "content": "/// The main function that tells which creatures evolute and devolute into which other creatures.\n\npub fn pokemon_op_sys(stack: &mut Stack<Creature>, operator: &Command) {\n\n use Creature::*;\n\n let last_creature = stack.pop();\n\n match operator {\n\n Command::Evolute => stack...
Rust
src/emac0/mmctxim.rs
tirust/msp432e4
479d52cb87a757f77406e1f314ea8acfba70f675
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::MMCTXIM { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct EMAC_MMCTXIM_GBFR { bits: bool, } impl EMAC_MMCTXIM_GBFR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_MMCTXIM_GBFW<'a> { w: &'a mut W, } impl<'a> _EMAC_MMCTXIM_GBFW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u32) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct EMAC_MMCTXIM_SCOLLGFR { bits: bool, } impl EMAC_MMCTXIM_SCOLLGFR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_MMCTXIM_SCOLLGFW<'a> { w: &'a mut W, } impl<'a> _EMAC_MMCTXIM_SCOLLGFW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 14); self.w.bits |= ((value as u32) & 1) << 14; self.w } } #[doc = r"Value of the field"] pub struct EMAC_MMCTXIM_MCOLLGFR { bits: bool, } impl EMAC_MMCTXIM_MCOLLGFR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_MMCTXIM_MCOLLGFW<'a> { w: &'a mut W, } impl<'a> _EMAC_MMCTXIM_MCOLLGFW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 15); self.w.bits |= ((value as u32) & 1) << 15; self.w } } #[doc = r"Value of the field"] pub struct EMAC_MMCTXIM_OCTCNTR { bits: bool, } impl EMAC_MMCTXIM_OCTCNTR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_MMCTXIM_OCTCNTW<'a> { w: &'a mut W, } impl<'a> _EMAC_MMCTXIM_OCTCNTW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 20); self.w.bits |= ((value as u32) & 1) << 20; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 1 - MMC Transmit Good Bad Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_gbf(&self) -> EMAC_MMCTXIM_GBFR { let bits = ((self.bits >> 1) & 1) != 0; EMAC_MMCTXIM_GBFR { bits } } #[doc = "Bit 14 - MMC Transmit Single Collision Good Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_scollgf(&self) -> EMAC_MMCTXIM_SCOLLGFR { let bits = ((self.bits >> 14) & 1) != 0; EMAC_MMCTXIM_SCOLLGFR { bits } } #[doc = "Bit 15 - MMC Transmit Multiple Collision Good Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_mcollgf(&self) -> EMAC_MMCTXIM_MCOLLGFR { let bits = ((self.bits >> 15) & 1) != 0; EMAC_MMCTXIM_MCOLLGFR { bits } } #[doc = "Bit 20 - MMC Transmit Good Octet Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_octcnt(&self) -> EMAC_MMCTXIM_OCTCNTR { let bits = ((self.bits >> 20) & 1) != 0; EMAC_MMCTXIM_OCTCNTR { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 1 - MMC Transmit Good Bad Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_gbf(&mut self) -> _EMAC_MMCTXIM_GBFW { _EMAC_MMCTXIM_GBFW { w: self } } #[doc = "Bit 14 - MMC Transmit Single Collision Good Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_scollgf(&mut self) -> _EMAC_MMCTXIM_SCOLLGFW { _EMAC_MMCTXIM_SCOLLGFW { w: self } } #[doc = "Bit 15 - MMC Transmit Multiple Collision Good Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_mcollgf(&mut self) -> _EMAC_MMCTXIM_MCOLLGFW { _EMAC_MMCTXIM_MCOLLGFW { w: self } } #[doc = "Bit 20 - MMC Transmit Good Octet Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_octcnt(&mut self) -> _EMAC_MMCTXIM_OCTCNTW { _EMAC_MMCTXIM_OCTCNTW { w: self } } }
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::MMCTXIM { #[doc = r"Modifies the contents of the register"] #[inline(always)]
#[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct EMAC_MMCTXIM_GBFR { bits: bool, } impl EMAC_MMCTXIM_GBFR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_MMCTXIM_GBFW<'a> { w: &'a mut W, } impl<'a> _EMAC_MMCTXIM_GBFW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u32) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct EMAC_MMCTXIM_SCOLLGFR { bits: bool, } impl EMAC_MMCTXIM_SCOLLGFR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_MMCTXIM_SCOLLGFW<'a> { w: &'a mut W, } impl<'a> _EMAC_MMCTXIM_SCOLLGFW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 14); self.w.bits |= ((value as u32) & 1) << 14; self.w } } #[doc = r"Value of the field"] pub struct EMAC_MMCTXIM_MCOLLGFR { bits: bool, } impl EMAC_MMCTXIM_MCOLLGFR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_MMCTXIM_MCOLLGFW<'a> { w: &'a mut W, } impl<'a> _EMAC_MMCTXIM_MCOLLGFW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 15); self.w.bits |= ((value as u32) & 1) << 15; self.w } } #[doc = r"Value of the field"] pub struct EMAC_MMCTXIM_OCTCNTR { bits: bool, } impl EMAC_MMCTXIM_OCTCNTR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_MMCTXIM_OCTCNTW<'a> { w: &'a mut W, } impl<'a> _EMAC_MMCTXIM_OCTCNTW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 20); self.w.bits |= ((value as u32) & 1) << 20; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 1 - MMC Transmit Good Bad Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_gbf(&self) -> EMAC_MMCTXIM_GBFR { let bits = ((self.bits >> 1) & 1) != 0; EMAC_MMCTXIM_GBFR { bits } } #[doc = "Bit 14 - MMC Transmit Single Collision Good Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_scollgf(&self) -> EMAC_MMCTXIM_SCOLLGFR { let bits = ((self.bits >> 14) & 1) != 0; EMAC_MMCTXIM_SCOLLGFR { bits } } #[doc = "Bit 15 - MMC Transmit Multiple Collision Good Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_mcollgf(&self) -> EMAC_MMCTXIM_MCOLLGFR { let bits = ((self.bits >> 15) & 1) != 0; EMAC_MMCTXIM_MCOLLGFR { bits } } #[doc = "Bit 20 - MMC Transmit Good Octet Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_octcnt(&self) -> EMAC_MMCTXIM_OCTCNTR { let bits = ((self.bits >> 20) & 1) != 0; EMAC_MMCTXIM_OCTCNTR { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 1 - MMC Transmit Good Bad Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_gbf(&mut self) -> _EMAC_MMCTXIM_GBFW { _EMAC_MMCTXIM_GBFW { w: self } } #[doc = "Bit 14 - MMC Transmit Single Collision Good Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_scollgf(&mut self) -> _EMAC_MMCTXIM_SCOLLGFW { _EMAC_MMCTXIM_SCOLLGFW { w: self } } #[doc = "Bit 15 - MMC Transmit Multiple Collision Good Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_mcollgf(&mut self) -> _EMAC_MMCTXIM_MCOLLGFW { _EMAC_MMCTXIM_MCOLLGFW { w: self } } #[doc = "Bit 20 - MMC Transmit Good Octet Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_octcnt(&mut self) -> _EMAC_MMCTXIM_OCTCNTW { _EMAC_MMCTXIM_OCTCNTW { w: self } } }
pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); }
function_block-full_function
[ { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::BIT {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify...
Rust
src/lib.rs
antialize/sql-parse
37ef1b698af74ab5952f7866512b81e0fbbb9deb
#![no_std] #![forbid(unsafe_code)] extern crate alloc; use alloc::vec::Vec; use lexer::Token; use parser::Parser; mod alter; mod create; mod data_type; mod delete; mod drop; mod expression; mod identifier; mod insert_replace; mod issue; mod keywords; mod lexer; mod parser; mod select; mod span; mod sstring; mod statement; mod update; pub use data_type::{DataType, DataTypeProperty, Type}; pub use identifier::Identifier; pub use issue::{Issue, Level}; pub use span::{OptSpanned, Span, Spanned}; pub use sstring::SString; pub use statement::{Statement, Union, UnionType, UnionWith}; pub use alter::{ AlterSpecification, AlterTable, ForeignKeyOn, ForeignKeyOnAction, ForeignKeyOnType, IndexCol, IndexOption, IndexType, }; pub use create::{ CreateAlgorithm, CreateDefinition, CreateFunction, CreateOption, CreateTable, CreateTrigger, CreateView, TableOption, }; pub use delete::{Delete, DeleteFlag}; pub use drop::{ DropDatabase, DropEvent, DropFunction, DropProcedure, DropServer, DropTable, DropTrigger, DropView, }; pub use expression::{ BinaryOperator, Expression, Function, IdentifierPart, Is, UnaryOperator, When, }; pub use insert_replace::{InsertReplace, InsertReplaceFlag, InsertReplaceType}; pub use select::{JoinSpecification, JoinType, Select, SelectFlag, TableReference}; pub use update::{Update, UpdateFlag}; #[derive(Clone, Debug)] pub enum SQLDialect { MariaDB, PostgreSQL, } impl SQLDialect { fn is_postgresql(&self) -> bool { matches!(self, SQLDialect::PostgreSQL) } } #[derive(Clone, Debug)] pub enum SQLArguments { None, Percent, QuestionMark, } #[derive(Clone, Debug)] pub struct ParseOptions { dialect: SQLDialect, arguments: SQLArguments, warn_unquoted_identifiers: bool, warn_none_capital_keywords: bool, list_hack: bool, } impl Default for ParseOptions { fn default() -> Self { Self { dialect: SQLDialect::MariaDB, arguments: SQLArguments::None, warn_none_capital_keywords: false, warn_unquoted_identifiers: false, list_hack: false, } } } impl ParseOptions { pub fn new() -> Self { Default::default() } pub fn dialect(self, dialect: SQLDialect) -> Self { Self { dialect, ..self } } pub fn arguments(self, arguments: SQLArguments) -> Self { Self { arguments, ..self } } pub fn warn_unquoted_identifiers(self, warn_unquoted_identifiers: bool) -> Self { Self { warn_unquoted_identifiers, ..self } } pub fn warn_none_capital_keywords(self, warn_none_capital_keywords: bool) -> Self { Self { warn_none_capital_keywords, ..self } } pub fn list_hack(self, list_hack: bool) -> Self { Self { list_hack, ..self } } } #[macro_export] macro_rules! issue_ice { ( $spanned:expr ) => {{ Issue::err( alloc::format!("Internal compiler error in {}:{}", file!(), line!()), $spanned, ) }}; } #[macro_export] macro_rules! issue_todo { ( $spanned:expr ) => {{ Issue::err( alloc::format!("Not yet implemented {}:{}", file!(), line!()), $spanned, ) }}; } pub fn parse_statements<'a>( src: &'a str, issues: &mut Vec<Issue>, options: &ParseOptions, ) -> Vec<Statement<'a>> { let mut parser = Parser::new(src, issues, options); statement::parse_statements(&mut parser) } pub fn parse_statement<'a>( src: &'a str, issues: &mut Vec<Issue>, options: &ParseOptions, ) -> Option<Statement<'a>> { let mut parser = Parser::new(src, issues, options); match statement::parse_statement(&mut parser) { Ok(Some(v)) => { if parser.token != Token::Eof { parser.expected_error("Unexpected token after statement") } Some(v) } Ok(None) => { parser.expected_error("Statement"); None } Err(_) => None, } }
#![no_std] #![forbid(unsafe_code)] extern crate alloc; use alloc::vec::Vec; use lexer::Token; use parser::Parser; mod alter; mod create; mod data_type; mod delete; mod drop; mod expression; mod identifier; mod insert_replace; mod issue; mod keywords; mod lexer; mod parser; mod select; mod span; mod sstring; mod statement; mod update; pub use data_type::{DataType, DataTypeProperty, Type}; pub use identifier::Identifier; pub use issue::{Issue, Level}; pub use span::{OptSpanned, Span, Spanned}; pub use sstring::SString; pub use statement::{Statement, Union, UnionType, UnionWith}; pub use alter::{ AlterSpecification, AlterTable, ForeignKeyOn, ForeignKeyOnAction, ForeignKeyOnType, IndexCol, IndexOption, IndexType, }; pub use create::{ CreateAlgorithm, CreateDefinition, CreateFunction, CreateOption, CreateTable, CreateTrigger, CreateView, TableOption, }; pub use delete::{Delete, DeleteFlag}; pub use drop::{ DropDatabase, DropEvent, DropFunction, DropProcedure, DropServer, DropTable, DropTrigger, DropView, }; pub use expression::{ BinaryOperator, Expression, Function, IdentifierPart, Is, UnaryOperator, When, }; pub use insert_replace::{InsertReplace, InsertReplaceFlag, InsertReplaceType}; pub use select::{JoinSpecification, JoinType, Select, SelectFlag, TableReference}; pub use update::{Update, UpdateFlag}; #[derive(Clone, Debug)] pub enum SQLDialect { MariaDB, PostgreSQL, } impl SQLDialect { fn is_postgresql(&self) -> bool { matches!(self, SQLDialect::PostgreSQL) } } #[derive(Clone, Debug)] pub enum SQLArguments { None, Percent, QuestionMark, } #[derive(Clone, Debug)] pub struct ParseOptions { dialect: SQLDialect, arguments: SQLArguments, warn_unquoted_identifiers: bool, warn_none_capital_keywords: bool, list_hack: bool, } impl Default for ParseOptions { fn default() -> Self { Self { dialect: SQLDialect::MariaDB, arguments: SQLArguments::None, warn_none_capital_keywords: false, warn_unquoted_identifiers: false, list_hack: false, } } } impl ParseOptions { pub fn new() -> Self { Default::default() } pub fn dialect(self, dialect: SQLDialect) -> Self { Self { dialect, ..self } } pub fn arguments(self, arguments: SQLArguments) -> Self { Self { arguments, ..self } } pub fn warn_unquoted_identifiers(self, warn_unquoted_identifiers: bool) -> Self { Self { warn_unquoted_identifiers, ..self } } pub fn warn_none_capital_keywords(self, warn_none_capital_keywords: bool) -> Self { Self { warn_none_capital_keywords, ..self } } pub fn list_hack(self, list_hack: bool) -> Self { Self { list_hack, ..self } } } #[macro_export] macro_rules! issue_ice { ( $spanned:expr ) => {{ Issue::err( alloc::format!("Internal compiler error in {}:{}", file!(), line!()), $spanned, ) }}; } #[macro_export] macro_rules! issue_todo { ( $spanned:expr ) => {{ Issue::err( alloc::format!("Not yet implemented {}:{}", file!(), line!()), $spanned, ) }}; } pub fn parse_statements<'a>( src: &'a str, issues: &mut Vec<Issue>, options: &ParseOptions, ) -> Vec<Statement<'a>> { let mut parser = Parser::new(src, issues, options); statement::parse_statements(&mut parser) } pub fn parse_statement<'a>( src: &'a str, issues: &mut Vec<Issue>, options: &ParseOptions, ) -> Option<Statement<'a>> { let mut parser = Parser::new(src, issues, options); match statement::parse_statement(&mut parser) { Ok(Some(v)) => {
if parser.token != Token::Eof { parser.expected_error("Unexpected token after statement") } Some(v) } Ok(None) => { parser.expected_error("Statement"); None } Err(_) => None, } }
function_block-function_prefix_line
[ { "content": "fn parse_width(parser: &mut Parser<'_, '_>) -> Result<Option<(usize, Span)>, ParseError> {\n\n if !matches!(parser.token, Token::LParen) {\n\n return Ok(None);\n\n }\n\n parser.consume_token(Token::LParen)?;\n\n let value = parser.recovered(\")\", &|t| t == &Token::RParen, |pars...
Rust
implementations/rust/ockam/signature_ps/src/signature.rs
psinghal20/ockam
55c2787eb2392c919156c6dded9f31a5249541e1
use crate::{PublicKey, SecretKey}; use blake2::{Blake2b, VarBlake2b}; use bls12_381_plus::{ multi_miller_loop, ExpandMsgXmd, G1Affine, G1Projective, G2Affine, G2Prepared, G2Projective, Scalar, }; use core::convert::TryFrom; use digest::{Update, VariableOutput}; use group::{Curve, Group}; use serde::{ de::{Error as DError, SeqAccess, Visitor}, ser::SerializeTuple, Deserialize, Deserializer, Serialize, Serializer, }; use signature_core::{constants::*, error::Error, lib::*, util::*}; use subtle::{Choice, CtOption}; #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct Signature { pub(crate) sigma_1: G1Projective, pub(crate) sigma_2: G1Projective, pub(crate) m_tick: Scalar, } impl Serialize for Signature { fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error> where S: Serializer, { let bytes = self.to_bytes(); let mut seq = s.serialize_tuple(bytes.len())?; for b in &bytes { seq.serialize_element(b)?; } seq.end() } } impl<'de> Deserialize<'de> for Signature { fn deserialize<D>(d: D) -> Result<Signature, D::Error> where D: Deserializer<'de>, { struct ArrayVisitor; impl<'de> Visitor<'de> for ArrayVisitor { type Value = Signature; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "expected byte array") } fn visit_seq<A>(self, mut seq: A) -> Result<Signature, A::Error> where A: SeqAccess<'de>, { let mut arr = [0u8; Signature::BYTES]; for i in 0..arr.len() { arr[i] = seq .next_element()? .ok_or_else(|| DError::invalid_length(i, &self))?; } let res = Signature::from_bytes(&arr); if res.is_some().unwrap_u8() == 1 { Ok(res.unwrap()) } else { Err(DError::invalid_value( serde::de::Unexpected::Bytes(&arr), &self, )) } } } d.deserialize_tuple(Signature::BYTES, ArrayVisitor) } } impl Default for Signature { fn default() -> Self { Self { sigma_1: G1Projective::identity(), sigma_2: G1Projective::identity(), m_tick: Scalar::zero(), } } } impl Signature { pub const BYTES: usize = 128; const DST: &'static [u8] = b"PS_SIG_BLS12381G1_XMD:BLAKE2B_SSWU_RO_"; pub fn new<M>(sk: &SecretKey, msgs: M) -> Result<Self, Error> where M: AsRef<[Message]>, { let msgs = msgs.as_ref(); if sk.y.len() < msgs.len() { return Err(Error::new(1, "secret key is not big enough")); } if sk.is_invalid() { return Err(Error::new(1, "invalid secret key")); } let mut hasher = VarBlake2b::new(48).unwrap(); for m in msgs { hasher.update(m.to_bytes()); } let mut out = [0u8; 48]; hasher.finalize_variable(|r| { out.copy_from_slice(r); }); let m_tick = Scalar::from_okm(&out); let sigma_1 = G1Projective::hash::<ExpandMsgXmd<Blake2b>>(&m_tick.to_bytes()[..], Self::DST); let mut exp = sk.x + sk.w * m_tick; for i in 0..msgs.len() { exp += sk.y[i] * msgs[i].0; } let sigma_2 = sigma_1 * exp; Ok(Self { sigma_1, sigma_2, m_tick, }) } pub fn verify<M>(&self, pk: &PublicKey, msgs: M) -> Choice where M: AsRef<[Message]>, { let msgs = msgs.as_ref(); if pk.y.len() < msgs.len() { return Choice::from(0); } if pk.is_invalid().unwrap_u8() == 1 { return Choice::from(0); } let mut points = Vec::<G2Projective, U130>::new(); let mut scalars = Vec::<Scalar, U130>::new(); points.push(pk.x).expect(ALLOC_MSG); scalars.push(Scalar::one()).expect(ALLOC_MSG); points.push(pk.w).expect(ALLOC_MSG); scalars.push(self.m_tick).expect(ALLOC_MSG); for i in 0..msgs.len() { points.push(pk.y[i]).expect(ALLOC_MSG); scalars.push(msgs[i].0).expect(ALLOC_MSG); } let y_m = G2Projective::sum_of_products_in_place(points.as_ref(), scalars.as_mut()); multi_miller_loop(&[ ( &self.sigma_1.to_affine(), &G2Prepared::from(y_m.to_affine()), ), ( &self.sigma_2.to_affine(), &G2Prepared::from(-G2Affine::generator()), ), ]) .final_exponentiation() .is_identity() } pub fn to_bytes(&self) -> [u8; Self::BYTES] { let mut bytes = [0u8; Self::BYTES]; bytes[..48].copy_from_slice(&self.sigma_1.to_affine().to_compressed()); bytes[48..96].copy_from_slice(&self.sigma_2.to_affine().to_compressed()); bytes[96..128].copy_from_slice(&scalar_to_bytes(self.m_tick)); bytes } pub fn from_bytes(data: &[u8; Self::BYTES]) -> CtOption<Self> { let s1 = G1Affine::from_compressed(slicer!(data, 0, 48, COMMITMENT_BYTES)) .map(|p| G1Projective::from(p)); let s2 = G1Affine::from_compressed(slicer!(data, 48, 96, COMMITMENT_BYTES)) .map(|p| G1Projective::from(p)); let m_t = scalar_from_bytes(slicer!(data, 96, 128, FIELD_BYTES)); s1.and_then(|sigma_1| { s2.and_then(|sigma_2| { m_t.and_then(|m_tick| { CtOption::new( Signature { sigma_1, sigma_2, m_tick, }, Choice::from(1), ) }) }) }) } }
use crate::{PublicKey, SecretKey}; use blake2::{Blake2b, VarBlake2b}; use bls12_381_plus::{ multi_miller_loop, ExpandMsgXmd, G1Affine, G1Projective, G2Affine, G2Prepared, G2Projective, Scalar, }; use core::convert::TryFrom; use digest::{Update, VariableOutput}; use group::{Curve, Group}; use serde::{ de::{Error as DError, SeqAccess, Visitor}, ser::SerializeTuple, Deserialize, Deserializer, Serialize, Serializer, }; use signature_core::{constants::*, error::Error, lib::*, util::*}; use subtle::{Choice, CtOption}; #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct Signature { pub(crate) sigma_1: G1Projective, pub(crate) sigma_2: G1Projective, pub(crate) m_tick: Scalar, } impl Serialize for Signature {
} impl<'de> Deserialize<'de> for Signature { fn deserialize<D>(d: D) -> Result<Signature, D::Error> where D: Deserializer<'de>, { struct ArrayVisitor; impl<'de> Visitor<'de> for ArrayVisitor { type Value = Signature; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "expected byte array") } fn visit_seq<A>(self, mut seq: A) -> Result<Signature, A::Error> where A: SeqAccess<'de>, { let mut arr = [0u8; Signature::BYTES]; for i in 0..arr.len() { arr[i] = seq .next_element()? .ok_or_else(|| DError::invalid_length(i, &self))?; } let res = Signature::from_bytes(&arr); if res.is_some().unwrap_u8() == 1 { Ok(res.unwrap()) } else { Err(DError::invalid_value( serde::de::Unexpected::Bytes(&arr), &self, )) } } } d.deserialize_tuple(Signature::BYTES, ArrayVisitor) } } impl Default for Signature { fn default() -> Self { Self { sigma_1: G1Projective::identity(), sigma_2: G1Projective::identity(), m_tick: Scalar::zero(), } } } impl Signature { pub const BYTES: usize = 128; const DST: &'static [u8] = b"PS_SIG_BLS12381G1_XMD:BLAKE2B_SSWU_RO_"; pub fn new<M>(sk: &SecretKey, msgs: M) -> Result<Self, Error> where M: AsRef<[Message]>, { let msgs = msgs.as_ref(); if sk.y.len() < msgs.len() { return Err(Error::new(1, "secret key is not big enough")); } if sk.is_invalid() { return Err(Error::new(1, "invalid secret key")); } let mut hasher = VarBlake2b::new(48).unwrap(); for m in msgs { hasher.update(m.to_bytes()); } let mut out = [0u8; 48]; hasher.finalize_variable(|r| { out.copy_from_slice(r); }); let m_tick = Scalar::from_okm(&out); let sigma_1 = G1Projective::hash::<ExpandMsgXmd<Blake2b>>(&m_tick.to_bytes()[..], Self::DST); let mut exp = sk.x + sk.w * m_tick; for i in 0..msgs.len() { exp += sk.y[i] * msgs[i].0; } let sigma_2 = sigma_1 * exp; Ok(Self { sigma_1, sigma_2, m_tick, }) } pub fn verify<M>(&self, pk: &PublicKey, msgs: M) -> Choice where M: AsRef<[Message]>, { let msgs = msgs.as_ref(); if pk.y.len() < msgs.len() { return Choice::from(0); } if pk.is_invalid().unwrap_u8() == 1 { return Choice::from(0); } let mut points = Vec::<G2Projective, U130>::new(); let mut scalars = Vec::<Scalar, U130>::new(); points.push(pk.x).expect(ALLOC_MSG); scalars.push(Scalar::one()).expect(ALLOC_MSG); points.push(pk.w).expect(ALLOC_MSG); scalars.push(self.m_tick).expect(ALLOC_MSG); for i in 0..msgs.len() { points.push(pk.y[i]).expect(ALLOC_MSG); scalars.push(msgs[i].0).expect(ALLOC_MSG); } let y_m = G2Projective::sum_of_products_in_place(points.as_ref(), scalars.as_mut()); multi_miller_loop(&[ ( &self.sigma_1.to_affine(), &G2Prepared::from(y_m.to_affine()), ), ( &self.sigma_2.to_affine(), &G2Prepared::from(-G2Affine::generator()), ), ]) .final_exponentiation() .is_identity() } pub fn to_bytes(&self) -> [u8; Self::BYTES] { let mut bytes = [0u8; Self::BYTES]; bytes[..48].copy_from_slice(&self.sigma_1.to_affine().to_compressed()); bytes[48..96].copy_from_slice(&self.sigma_2.to_affine().to_compressed()); bytes[96..128].copy_from_slice(&scalar_to_bytes(self.m_tick)); bytes } pub fn from_bytes(data: &[u8; Self::BYTES]) -> CtOption<Self> { let s1 = G1Affine::from_compressed(slicer!(data, 0, 48, COMMITMENT_BYTES)) .map(|p| G1Projective::from(p)); let s2 = G1Affine::from_compressed(slicer!(data, 48, 96, COMMITMENT_BYTES)) .map(|p| G1Projective::from(p)); let m_t = scalar_from_bytes(slicer!(data, 96, 128, FIELD_BYTES)); s1.and_then(|sigma_1| { s2.and_then(|sigma_2| { m_t.and_then(|m_tick| { CtOption::new( Signature { sigma_1, sigma_2, m_tick, }, Choice::from(1), ) }) }) }) } }
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error> where S: Serializer, { let bytes = self.to_bytes(); let mut seq = s.serialize_tuple(bytes.len())?; for b in &bytes { seq.serialize_element(b)?; } seq.end() }
function_block-full_function
[ { "content": "/// Convert a big endian byte sequence to a Scalar\n\npub fn scalar_from_bytes(bytes: &[u8; 32]) -> CtOption<Scalar> {\n\n let mut t = [0u8; 32];\n\n t.copy_from_slice(bytes);\n\n t.reverse();\n\n Scalar::from_bytes(&t)\n\n}\n\n\n", "file_path": "implementations/rust/ockam/signatur...
Rust
crates/history/src/browser.rs
kolloch/gloo
07e7dfa9c67d74c871f82fca54a1d7b5a0b9fce7
use std::any::Any; use std::borrow::Cow; use std::cell::RefCell; use std::fmt; use std::rc::Rc; use gloo_events::EventListener; use gloo_utils::window; #[cfg(feature = "query")] use serde::Serialize; use wasm_bindgen::{JsValue, UnwrapThrowExt}; use web_sys::Url; #[cfg(feature = "query")] use crate::error::HistoryResult; use crate::history::History; use crate::listener::HistoryListener; use crate::location::Location; use crate::state::{HistoryState, StateMap}; use crate::utils::WeakCallback; #[derive(Clone)] pub struct BrowserHistory { inner: web_sys::History, states: Rc<RefCell<StateMap>>, callbacks: Rc<RefCell<Vec<WeakCallback>>>, } impl fmt::Debug for BrowserHistory { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("BrowserHistory").finish() } } impl PartialEq for BrowserHistory { fn eq(&self, _rhs: &Self) -> bool { true } } impl History for BrowserHistory { fn len(&self) -> usize { self.inner.length().expect_throw("failed to get length.") as usize } fn go(&self, delta: isize) { self.inner .go_with_delta(delta as i32) .expect_throw("failed to call go.") } fn push<'a>(&self, route: impl Into<Cow<'a, str>>) { let url = route.into(); self.inner .push_state_with_url(&Self::create_history_state().1, "", Some(&url)) .expect_throw("failed to push state."); self.notify_callbacks(); } fn replace<'a>(&self, route: impl Into<Cow<'a, str>>) { let url = route.into(); self.inner .replace_state_with_url(&Self::create_history_state().1, "", Some(&url)) .expect_throw("failed to replace history."); self.notify_callbacks(); } fn push_with_state<'a, T>(&self, route: impl Into<Cow<'a, str>>, state: T) where T: 'static, { let url = route.into(); let (id, history_state) = Self::create_history_state(); let mut states = self.states.borrow_mut(); states.insert(id, Rc::new(state) as Rc<dyn Any>); self.inner .push_state_with_url(&history_state, "", Some(&url)) .expect_throw("failed to push state."); self.notify_callbacks(); } fn replace_with_state<'a, T>(&self, route: impl Into<Cow<'a, str>>, state: T) where T: 'static, { let url = route.into(); let (id, history_state) = Self::create_history_state(); let mut states = self.states.borrow_mut(); states.insert(id, Rc::new(state) as Rc<dyn Any>); self.inner .replace_state_with_url(&history_state, "", Some(&url)) .expect_throw("failed to replace state."); self.notify_callbacks(); } #[cfg(feature = "query")] fn push_with_query<'a, Q>(&self, route: impl Into<Cow<'a, str>>, query: Q) -> HistoryResult<()> where Q: Serialize, { let route = route.into(); let query = serde_urlencoded::to_string(query)?; let url = Self::combine_url(&route, &query); self.inner .push_state_with_url(&Self::create_history_state().1, "", Some(&url)) .expect_throw("failed to push history."); self.notify_callbacks(); Ok(()) } #[cfg(feature = "query")] fn replace_with_query<'a, Q>( &self, route: impl Into<Cow<'a, str>>, query: Q, ) -> HistoryResult<()> where Q: Serialize, { let route = route.into(); let query = serde_urlencoded::to_string(query)?; let url = Self::combine_url(&route, &query); self.inner .replace_state_with_url(&Self::create_history_state().1, "", Some(&url)) .expect_throw("failed to replace history."); self.notify_callbacks(); Ok(()) } #[cfg(all(feature = "query"))] fn push_with_query_and_state<'a, Q, T>( &self, route: impl Into<Cow<'a, str>>, query: Q, state: T, ) -> HistoryResult<()> where Q: Serialize, T: 'static, { let (id, history_state) = Self::create_history_state(); let mut states = self.states.borrow_mut(); states.insert(id, Rc::new(state) as Rc<dyn Any>); let route = route.into(); let query = serde_urlencoded::to_string(query)?; let url = Self::combine_url(&route, &query); self.inner .push_state_with_url(&history_state, "", Some(&url)) .expect_throw("failed to push history."); self.notify_callbacks(); Ok(()) } #[cfg(all(feature = "query"))] fn replace_with_query_and_state<'a, Q, T>( &self, route: impl Into<Cow<'a, str>>, query: Q, state: T, ) -> HistoryResult<()> where Q: Serialize, T: 'static, { let (id, history_state) = Self::create_history_state(); let mut states = self.states.borrow_mut(); states.insert(id, Rc::new(state) as Rc<dyn Any>); let route = route.into(); let query = serde_urlencoded::to_string(query)?; let url = Self::combine_url(&route, &query); self.inner .replace_state_with_url(&history_state, "", Some(&url)) .expect_throw("failed to replace history."); self.notify_callbacks(); Ok(()) } fn listen<CB>(&self, callback: CB) -> HistoryListener where CB: Fn() + 'static, { let cb = Rc::new(callback) as Rc<dyn Fn()>; self.callbacks.borrow_mut().push(Rc::downgrade(&cb)); HistoryListener { _listener: cb } } fn location(&self) -> Location { let loc = window().location(); let history_state = self.inner.state().expect_throw("failed to get state"); let history_state = serde_wasm_bindgen::from_value::<HistoryState>(history_state).ok(); let id = history_state.map(|m| m.id()); let states = self.states.borrow(); Location { path: loc.pathname().expect_throw("failed to get pathname").into(), query_str: loc .search() .expect_throw("failed to get location query.") .into(), hash: loc .hash() .expect_throw("failed to get location hash.") .into(), state: id.and_then(|m| states.get(&m).cloned()), id, } } } impl Default for BrowserHistory { fn default() -> Self { thread_local! { static BROWSER_HISTORY: RefCell<Option<BrowserHistory>> = RefCell::default(); static LISTENER: RefCell<Option<EventListener>> = RefCell::default(); } BROWSER_HISTORY.with(|m| { let mut m = m.borrow_mut(); match *m { Some(ref m) => m.clone(), None => { let window = window(); let inner = window .history() .expect_throw("Failed to create browser history. Are you using a browser?"); let callbacks = Rc::default(); let history = Self { inner, callbacks, states: Rc::default(), }; { let history = history.clone(); LISTENER.with(move |m| { let mut listener = m.borrow_mut(); *listener = Some(EventListener::new(&window, "popstate", move |_| { history.notify_callbacks(); })); }); } *m = Some(history.clone()); history } } }) } } impl BrowserHistory { pub fn new() -> Self { Self::default() } fn notify_callbacks(&self) { crate::utils::notify_callbacks(self.callbacks.clone()); } fn create_history_state() -> (u32, JsValue) { let history_state = HistoryState::new(); ( history_state.id(), serde_wasm_bindgen::to_value(&history_state) .expect_throw("fails to create history state."), ) } pub(crate) fn combine_url(route: &str, query: &str) -> String { let href = window() .location() .href() .expect_throw("Failed to read location href"); let url = Url::new_with_base(route, &href).expect_throw("current url is not valid."); url.set_search(query); url.href() } }
use std::any::Any; use std::borrow::Cow; use std::cell::RefCell; use std::fmt; use std::rc::Rc; use gloo_events::EventListener; use gloo_utils::window; #[cfg(feature = "query")] use serde::Serialize; use wasm_bindgen::{JsValue, UnwrapThrowExt}; use web_sys::Url; #[cfg(feature = "query")] use crate::error::HistoryResult; use crate::history::History; use crate::listener::HistoryListener; use crate::location::Location; use crate::state::{HistoryState, StateMap}; use crate::utils::WeakCallback; #[derive(Clone)] pub struct BrowserHistory { inner: web_sys::History, states: Rc<RefCell<StateMap>>, callbacks: Rc<RefCell<Vec<WeakCallback>>>, } impl fmt::Debug for BrowserHistory { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("BrowserHistory").finish() } } impl PartialEq for BrowserHistory { fn eq(&self, _rhs: &Self) -> bool { true } } impl History for BrowserHistory { fn len(&self) -> usize { self.inner.length().expect_throw("failed to get length.") as usize } fn go(&self, delta: isize) { self.inner .go_with_delta(delta as i32) .expect_throw("failed to call go.") } fn push<'a>(&self, route: impl Into<Cow<'a, str>>) { let url = route.into(); self.inner .push_state_with_url(&Self::create_history_state().1, "", Some(&url)) .expect_throw("failed to push state."); self.notify_callbacks(); } fn replace<'a>(&self, route: impl Into<Cow<'a, str>>) { let url = route.into(); self.inner .replace_state_with_url(&Self::create_history_state().1, "", Some(&url)) .expect_throw("failed to replace history."); self.notify_callbacks(); } fn push_with_state<'a, T>(&self, route: impl Into<Cow<'a, str>>, state: T) where T: 'static, { let url = route.into(); let (id, history_state) = Self::create_history_state(); let mut states = self.states.borrow_mut(); states.insert(id, Rc::new(state) as Rc<dyn Any>); self.inner .push_state_with_url(&history_state, "", Some(&url)) .expect_throw("failed to push state."); self.notify_callbacks(); } fn replace_with_state<'a, T>(&self, route: impl Into<Cow<'a, str>>, state: T) where T: 'static, { let url = route.into(); let (id, history_state) = Self::create_history_state();
.into(), hash: loc .hash() .expect_throw("failed to get location hash.") .into(), state: id.and_then(|m| states.get(&m).cloned()), id, } } } impl Default for BrowserHistory { fn default() -> Self { thread_local! { static BROWSER_HISTORY: RefCell<Option<BrowserHistory>> = RefCell::default(); static LISTENER: RefCell<Option<EventListener>> = RefCell::default(); } BROWSER_HISTORY.with(|m| { let mut m = m.borrow_mut(); match *m { Some(ref m) => m.clone(), None => { let window = window(); let inner = window .history() .expect_throw("Failed to create browser history. Are you using a browser?"); let callbacks = Rc::default(); let history = Self { inner, callbacks, states: Rc::default(), }; { let history = history.clone(); LISTENER.with(move |m| { let mut listener = m.borrow_mut(); *listener = Some(EventListener::new(&window, "popstate", move |_| { history.notify_callbacks(); })); }); } *m = Some(history.clone()); history } } }) } } impl BrowserHistory { pub fn new() -> Self { Self::default() } fn notify_callbacks(&self) { crate::utils::notify_callbacks(self.callbacks.clone()); } fn create_history_state() -> (u32, JsValue) { let history_state = HistoryState::new(); ( history_state.id(), serde_wasm_bindgen::to_value(&history_state) .expect_throw("fails to create history state."), ) } pub(crate) fn combine_url(route: &str, query: &str) -> String { let href = window() .location() .href() .expect_throw("Failed to read location href"); let url = Url::new_with_base(route, &href).expect_throw("current url is not valid."); url.set_search(query); url.href() } }
let mut states = self.states.borrow_mut(); states.insert(id, Rc::new(state) as Rc<dyn Any>); self.inner .replace_state_with_url(&history_state, "", Some(&url)) .expect_throw("failed to replace state."); self.notify_callbacks(); } #[cfg(feature = "query")] fn push_with_query<'a, Q>(&self, route: impl Into<Cow<'a, str>>, query: Q) -> HistoryResult<()> where Q: Serialize, { let route = route.into(); let query = serde_urlencoded::to_string(query)?; let url = Self::combine_url(&route, &query); self.inner .push_state_with_url(&Self::create_history_state().1, "", Some(&url)) .expect_throw("failed to push history."); self.notify_callbacks(); Ok(()) } #[cfg(feature = "query")] fn replace_with_query<'a, Q>( &self, route: impl Into<Cow<'a, str>>, query: Q, ) -> HistoryResult<()> where Q: Serialize, { let route = route.into(); let query = serde_urlencoded::to_string(query)?; let url = Self::combine_url(&route, &query); self.inner .replace_state_with_url(&Self::create_history_state().1, "", Some(&url)) .expect_throw("failed to replace history."); self.notify_callbacks(); Ok(()) } #[cfg(all(feature = "query"))] fn push_with_query_and_state<'a, Q, T>( &self, route: impl Into<Cow<'a, str>>, query: Q, state: T, ) -> HistoryResult<()> where Q: Serialize, T: 'static, { let (id, history_state) = Self::create_history_state(); let mut states = self.states.borrow_mut(); states.insert(id, Rc::new(state) as Rc<dyn Any>); let route = route.into(); let query = serde_urlencoded::to_string(query)?; let url = Self::combine_url(&route, &query); self.inner .push_state_with_url(&history_state, "", Some(&url)) .expect_throw("failed to push history."); self.notify_callbacks(); Ok(()) } #[cfg(all(feature = "query"))] fn replace_with_query_and_state<'a, Q, T>( &self, route: impl Into<Cow<'a, str>>, query: Q, state: T, ) -> HistoryResult<()> where Q: Serialize, T: 'static, { let (id, history_state) = Self::create_history_state(); let mut states = self.states.borrow_mut(); states.insert(id, Rc::new(state) as Rc<dyn Any>); let route = route.into(); let query = serde_urlencoded::to_string(query)?; let url = Self::combine_url(&route, &query); self.inner .replace_state_with_url(&history_state, "", Some(&url)) .expect_throw("failed to replace history."); self.notify_callbacks(); Ok(()) } fn listen<CB>(&self, callback: CB) -> HistoryListener where CB: Fn() + 'static, { let cb = Rc::new(callback) as Rc<dyn Fn()>; self.callbacks.borrow_mut().push(Rc::downgrade(&cb)); HistoryListener { _listener: cb } } fn location(&self) -> Location { let loc = window().location(); let history_state = self.inner.state().expect_throw("failed to get state"); let history_state = serde_wasm_bindgen::from_value::<HistoryState>(history_state).ok(); let id = history_state.map(|m| m.id()); let states = self.states.borrow(); Location { path: loc.pathname().expect_throw("failed to get pathname").into(), query_str: loc .search() .expect_throw("failed to get location query.")
random
[ { "content": "/// Calls the confirm function.\n\n///\n\n/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm)\n\npub fn confirm(message: &str) -> bool {\n\n window().confirm_with_message(message).unwrap_throw()\n\n}\n\n\n", "file_path": "crates/dialogs/src/lib.rs", ...
Rust
src/transformers/dominance.rs
EclecticGriffin/Bril-Toolkit
a72ce7a7d2ca235ec9e544a713638df408d1828c
use super::cfg::{Node, Block}; use crate::serde_structs::structs::{Instr, Label}; use std::rc::{Rc, Weak}; use std::collections::{HashMap, HashSet}; use crate::analysis::dehydrated::{set_intersection, set_union}; use std::collections::VecDeque; fn reverse_post_order(root: &Rc<Node>) -> Vec<Rc<Node>> { let mut process_queue = Vec::<Rc<Node>>::new(); let mut exit_queue = Vec::<Rc<Node>>::new(); process_queue.push(root.clone()); while let Some(current) = process_queue.last() { let successors = current.successor_refs(); if successors.is_empty() { exit_queue.push(process_queue.pop().unwrap()); } else { let not_processed: Vec<&Rc<Node>> = successors.iter().filter(|x| !exit_queue.contains(x) && *x != current).collect(); if not_processed.is_empty() { exit_queue.push(process_queue.pop().unwrap()); } else if not_processed.iter().all(|x| process_queue.contains(x)) { exit_queue.push(process_queue.pop().unwrap()); } else { for item in not_processed.into_iter() { if !process_queue.contains(item) { process_queue.push(item.clone()); } } } } } exit_queue.reverse(); exit_queue } pub fn determine_dominators(nodes: &[Rc<Node>]) -> HashMap<Label, HashSet<Label>> { let mut label_map = HashMap::<Label, HashSet<Label>>::new(); let ordering = reverse_post_order(&nodes[0]); { let mut dom_set = HashSet::<Label>::new(); for node in ordering.iter() { dom_set.insert(node.label()); } for node in ordering.iter(){ label_map.insert(node.label(), dom_set.clone()); } } let mut changed = true; while changed { changed = false; for node in ordering.iter() { let preds = node.predecessor_labels(); let sets: Vec<&HashSet<Label>> = preds.into_iter().map(|x| {&label_map[&x]}).collect(); let intersect = set_intersection(sets); let mut current = HashSet::<Label>::with_capacity(1); current.insert(node.label()); let new_value = set_union(vec! [&intersect, &current ]); if new_value != label_map[&node.label()] { changed = true; label_map.insert(node.label(), new_value); } } } label_map } pub struct DominanceTree { nodes: HashMap<Label, Rc<Node>>, dominated_map: HashMap<Label, HashSet<Label>>, dom_tree: HashMap<Label, Vec<Label>>, root_label: Label } impl DominanceTree { pub fn new(nodes: &[Rc<Node>]) -> Self { let mut node_map = HashMap::<Label, Rc<Node>>::new(); for node in nodes { node_map.insert(node.label(), node.clone()); } let (dom_tree, dominated_map) = construct_dominance_tree(nodes); DominanceTree { nodes: node_map, dom_tree, dominated_map, root_label: nodes[0].label() } } pub fn lookup_node(&self, label: &Label) -> &Rc<Node> { &self.nodes[label] } pub fn root_node(&self) -> &Rc<Node> { self.lookup_node(&self.root_label) } pub fn get_children(&self, label: &Label) -> Vec<Rc<Node>> { self.dom_tree[label].iter() .map(|x| {self.lookup_node(x)}) .cloned() .collect() } pub fn compute_frontier(&self, target_label: &Label) -> Vec<Label> { let mut processing_queue: Vec<Label> = self.lookup_node(target_label).successor_labels(); let mut frontier = Vec::<Label>::new(); let mut processed: HashSet<Label> = HashSet::new(); processed.insert(*target_label); while let Some(current) = processing_queue.pop() { if self.dominated_map[&current].contains(target_label) { processed.insert(current); for successor_label in self.lookup_node(&current).successor_labels() { if !processed.contains(&successor_label) { processing_queue.push(successor_label); } else if successor_label == *target_label && !frontier.contains(target_label) { frontier.push(successor_label); } } } else { frontier.push(current); } } frontier } } fn construct_dominance_tree(nodes: &[Rc<Node>]) -> (HashMap<Label, Vec<Label>>, HashMap<Label, HashSet<Label>>){ let dominance_map = determine_dominators(nodes); let mut label_map = HashMap::<Label, Rc<Node>>::new(); let mut immediate_dominance_map = HashMap::<Label, Vec<Label>>::new(); for node in nodes { label_map.insert(node.label(), node.clone()); immediate_dominance_map.insert(node.label(), Vec::new()); } for node in nodes { for successor_label in node.successor_refs().iter().map(|x| x.label()) { if dominance_map[&successor_label].contains(&node.label()) && node.label() != successor_label { immediate_dominance_map.get_mut(&node.label()).unwrap().push(successor_label); } } } (immediate_dominance_map, dominance_map) }
use super::cfg::{Node, Block}; use crate::serde_structs::structs::{Instr, Label}; use std::rc::{Rc, Weak}; use std::collections::{HashMap, HashSet}; use crate::analysis::dehydrated::{set_intersection, set_union}; use std::collections::VecDeque; fn reverse_post_order(root: &Rc<Node>) -> Vec<Rc<Node>> { let mut process_queue = Vec::<Rc<Node>>::new(); let mut exit_queue = Vec::<Rc<Node>>::new(); process_queue.push(root.clone()); while let Some(current) = process_queue.last() { let successors = current.successor_refs(); if successors.is_empty() { exit_queue.push(process_queue.pop().unwrap()); } else { let not_processed: Vec<&Rc<Node>> = successors.iter().filter(|x| !exit_queue.contains(x) && *x != current).collect(); if not_processed.is_empty() { exit_queue.push(process_queue.pop().unwrap()); } else if not_processed.iter().all(|x| process_queue.contains(x)) { exit_queue.push(process_queue.pop().unwrap()); } else { for item in not_processed.into_iter() { if !process_queue.contains(item) { process_queue.push(item.clone()); } } } } } exit_queue.reverse(); exit_queue } pub fn determine_dominators(nodes: &[Rc<Node>]) -> HashMap<Label, HashSet<Label>> { let mut label_map = HashMap::<Label, HashSet<Label>>::new(); le
pub struct DominanceTree { nodes: HashMap<Label, Rc<Node>>, dominated_map: HashMap<Label, HashSet<Label>>, dom_tree: HashMap<Label, Vec<Label>>, root_label: Label } impl DominanceTree { pub fn new(nodes: &[Rc<Node>]) -> Self { let mut node_map = HashMap::<Label, Rc<Node>>::new(); for node in nodes { node_map.insert(node.label(), node.clone()); } let (dom_tree, dominated_map) = construct_dominance_tree(nodes); DominanceTree { nodes: node_map, dom_tree, dominated_map, root_label: nodes[0].label() } } pub fn lookup_node(&self, label: &Label) -> &Rc<Node> { &self.nodes[label] } pub fn root_node(&self) -> &Rc<Node> { self.lookup_node(&self.root_label) } pub fn get_children(&self, label: &Label) -> Vec<Rc<Node>> { self.dom_tree[label].iter() .map(|x| {self.lookup_node(x)}) .cloned() .collect() } pub fn compute_frontier(&self, target_label: &Label) -> Vec<Label> { let mut processing_queue: Vec<Label> = self.lookup_node(target_label).successor_labels(); let mut frontier = Vec::<Label>::new(); let mut processed: HashSet<Label> = HashSet::new(); processed.insert(*target_label); while let Some(current) = processing_queue.pop() { if self.dominated_map[&current].contains(target_label) { processed.insert(current); for successor_label in self.lookup_node(&current).successor_labels() { if !processed.contains(&successor_label) { processing_queue.push(successor_label); } else if successor_label == *target_label && !frontier.contains(target_label) { frontier.push(successor_label); } } } else { frontier.push(current); } } frontier } } fn construct_dominance_tree(nodes: &[Rc<Node>]) -> (HashMap<Label, Vec<Label>>, HashMap<Label, HashSet<Label>>){ let dominance_map = determine_dominators(nodes); let mut label_map = HashMap::<Label, Rc<Node>>::new(); let mut immediate_dominance_map = HashMap::<Label, Vec<Label>>::new(); for node in nodes { label_map.insert(node.label(), node.clone()); immediate_dominance_map.insert(node.label(), Vec::new()); } for node in nodes { for successor_label in node.successor_refs().iter().map(|x| x.label()) { if dominance_map[&successor_label].contains(&node.label()) && node.label() != successor_label { immediate_dominance_map.get_mut(&node.label()).unwrap().push(successor_label); } } } (immediate_dominance_map, dominance_map) }
t ordering = reverse_post_order(&nodes[0]); { let mut dom_set = HashSet::<Label>::new(); for node in ordering.iter() { dom_set.insert(node.label()); } for node in ordering.iter(){ label_map.insert(node.label(), dom_set.clone()); } } let mut changed = true; while changed { changed = false; for node in ordering.iter() { let preds = node.predecessor_labels(); let sets: Vec<&HashSet<Label>> = preds.into_iter().map(|x| {&label_map[&x]}).collect(); let intersect = set_intersection(sets); let mut current = HashSet::<Label>::with_capacity(1); current.insert(node.label()); let new_value = set_union(vec! [&intersect, &current ]); if new_value != label_map[&node.label()] { changed = true; label_map.insert(node.label(), new_value); } } } label_map }
function_block-function_prefixed
[ { "content": "pub fn connect_basic_blocks(blocks: &mut Vec<Rc<Node>>) {\n\n let map = construct_label_lookup(blocks);\n\n let mut second_iter = blocks.iter();\n\n second_iter.next();\n\n\n\n for (current, node) in blocks.iter().zip(second_iter) {\n\n connect_block(current, node, &map)\n\n ...
Rust
main/src/main.rs
kirch7/shaat
1479561bc3d8329940f693c7708e7cfa71a3fcc9
#[macro_use] extern crate actix; extern crate actix_web; extern crate cookie; extern crate crypto; #[macro_use] extern crate diesel; extern crate env_logger; extern crate futures; #[macro_use] extern crate juniper; #[macro_use] extern crate lazy_static; extern crate listenfd; extern crate messages; extern crate r2d2; #[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_json; extern crate static_cache; extern crate time; use actix::{Addr, Arbiter, Syn, SyncArbiter}; use actix_web::middleware::Logger; use actix_web::{http::Method, App, HttpResponse}; use diesel::r2d2::ConnectionManager; use diesel::SqliteConnection; use std::sync::Arc; mod auth; mod db; mod graphql; mod messajes; mod statiq; mod users; mod ws; use auth::{CookieIdentityPolicy, IdentityService}; fn main() -> Result<(), Box<dyn std::error::Error>> { ::std::env::set_var("RUST_LOG", "actix_web=info"); let addr = get_envvar("SHAAT_ADDR").ok_or("SHAAT_ADDR must be set")?; let db_addr = get_envvar("SHAAT_DB").ok_or("SHAAT_DB must be set")?; let _ = get_envvar("SHAAT_STATIC").ok_or("SHAAT_STATIC must be set")?; env_logger::init(); println!("loading users"); users::load(&db_addr).unwrap(); println!("loading messages"); messajes::load(&db_addr).unwrap(); println!("Okay"); println!("http://{}", addr); let sys = actix::System::new("shaat"); let a_server: Addr<Syn, _> = Arbiter::start(|_| ws::ChatServer::default()); let db_manager = ConnectionManager::<SqliteConnection>::new(db_addr); let db_pool = r2d2::Pool::builder().build(db_manager)?; let db_server = SyncArbiter::start(1, move || db::DbExecutor(db_pool.clone())); let schema = Arc::new(graphql::create_schema()); let graphql_addr = SyncArbiter::start(1, move || graphql::GraphQLExecutor::new(schema.clone())); let http_server = actix_web::server::new(move || { let ws_state = ws::WsChatSessionState { addr: a_server.clone(), username: String::default(), }; let db_state = db::State { db: db_server.clone(), }; let graphql_state = graphql::AppState { executor: graphql_addr.clone(), }; vec![ App::new() .middleware(Logger::default()) .prefix("/static") .resource("/{filename}", |r| r.f(statiq::handle_static)) .boxed(), App::with_state((ws_state, db_state, graphql_state)) .middleware(Logger::default()) .middleware(IdentityService::new( CookieIdentityPolicy::new(&[0; 32]) .name("shaat-auth") .secure(false), )) .resource("/ws/", |r| r.get().f(ws::handle_ws)) .resource("/graphql", |r| { r.method(Method::POST).with(graphql::graphql) }) .resource("/graphiql", |r| r.method(Method::GET).f(graphql::graphiql)) .resource("/login", |r| { r.method(Method::POST).with(auth::handle_login_post); r.method(Method::GET).f(auth::handle_login_get); }) .resource("/logout", |r| r.f(auth::handle_logout)) .resource("/", |r| r.f(auth::handle_index)) .boxed(), ] }); let mut manager = listenfd::ListenFd::from_env(); let http_server = if let Some(li) = manager.take_tcp_listener(0).map_err(|e| e.to_string())? { http_server.listen(li) } else { http_server.bind(addr).map_err(|e| e.to_string())? }; http_server.start(); let _ = sys.run(); Ok(()) } #[inline] fn get_envvar(key: &str) -> Option<String> { std::env::vars() .find(|(key_, _value)| key_ == key) .map(|(_key, value)| value) } #[inline] fn bad_request() -> HttpResponse { HttpResponse::BadRequest().finish() }
#[macro_use] extern crate actix; extern crate actix_web; extern crate cookie; extern crate crypto; #[macro_use] extern crate diesel; extern crate env_logger; extern crate futures; #[macro_use] extern crate juniper; #[macro_use] extern crate lazy_static; extern crate listenfd; extern crate messages; extern crate r2d2; #[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_json; extern crate static_cache; extern crate time; use actix::{Addr, Arbiter, Syn, SyncArbiter}; use actix_web::middleware::Logger; use actix_web::{http::Method, App, HttpResponse}; use diesel::r2d2::ConnectionManager; use diesel::SqliteConnection; use std::sync::Arc; mod auth; mod db; mod graphql; mod messajes; mod statiq; mod users; mod ws; use auth::{CookieIdentityPolicy, IdentityService}; fn main() -> Result<(), Box<dyn std::error::Error>> { ::std::env::set_var("RUST_LOG", "actix_web=info"); let addr = get_envvar("SHAAT_ADDR").ok_or("SHAAT_ADDR must be set")?; let db_addr = get_envvar("SHAAT_DB").ok_or("SHAAT_DB must be set")?; let _ = get_envvar("SHAAT_STATIC").ok_or("SHAAT_STATIC must be set")?; env_logger::init(); println!("loading users"); users::load(&db_addr).unwrap(); println!("loading messages"); messajes::load(&db_addr).unwrap(); println!("Okay"); println!("http://{}", addr); let sys = actix::System::new("shaat"); let a_server: Addr<Syn, _> = Arbiter::start(|_| ws::ChatServer::default()); let db_manager = ConnectionManager::<SqliteConnection>::new(db_addr); let db_pool = r2d2::Pool::builder().build(db_manager)?; let db_server = SyncArbiter::start(1, move || db::DbExecutor(db_pool.clone())); let schema = Arc::new(graphql::create_schema()); let graphql_addr = SyncArbiter::start(1, move || graphql::GraphQLExecutor::new(schema.clone())); let http_server = actix_web::server::new(move || { let ws_state = ws::WsChatSessionState { addr: a_server.clone(), username: String::default(), }; let db_state = db::State { db: db_server.clone(), };
#[inline] fn get_envvar(key: &str) -> Option<String> { std::env::vars() .find(|(key_, _value)| key_ == key) .map(|(_key, value)| value) } #[inline] fn bad_request() -> HttpResponse { HttpResponse::BadRequest().finish() }
let graphql_state = graphql::AppState { executor: graphql_addr.clone(), }; vec![ App::new() .middleware(Logger::default()) .prefix("/static") .resource("/{filename}", |r| r.f(statiq::handle_static)) .boxed(), App::with_state((ws_state, db_state, graphql_state)) .middleware(Logger::default()) .middleware(IdentityService::new( CookieIdentityPolicy::new(&[0; 32]) .name("shaat-auth") .secure(false), )) .resource("/ws/", |r| r.get().f(ws::handle_ws)) .resource("/graphql", |r| { r.method(Method::POST).with(graphql::graphql) }) .resource("/graphiql", |r| r.method(Method::GET).f(graphql::graphiql)) .resource("/login", |r| { r.method(Method::POST).with(auth::handle_login_post); r.method(Method::GET).f(auth::handle_login_get); }) .resource("/logout", |r| r.f(auth::handle_logout)) .resource("/", |r| r.f(auth::handle_index)) .boxed(), ] }); let mut manager = listenfd::ListenFd::from_env(); let http_server = if let Some(li) = manager.take_tcp_listener(0).map_err(|e| e.to_string())? { http_server.listen(li) } else { http_server.bind(addr).map_err(|e| e.to_string())? }; http_server.start(); let _ = sys.run(); Ok(()) }
function_block-function_prefix_line
[ { "content": "pub fn load(db: &str) -> Result<(), ()> {\n\n let db = SqliteConnection::establish(db).unwrap();\n\n\n\n let mut users = USERS.write().unwrap();\n\n ::db::schema::users::dsl::users\n\n .load::<::db::models::User>(&db)\n\n .map_err(|_| ())?\n\n .iter()\n\n .map(...
Rust
src/test/instruction_tests/instr_vcvtps2uqq.rs
ftilde/rust-x86asm
f6584b8cfe8e75d978bf7b83a67c69444fd3f161
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vcvtps2uqq_1() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM4)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K5), broadcast: None, }, &[98, 241, 125, 141, 121, 212], OperandSize::Dword, ) } #[test] fn vcvtps2uqq_2() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledDisplaced( ECX, Four, 782247532, Some(OperandSize::Qword), None, )), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), broadcast: None, }, &[98, 241, 125, 143, 121, 52, 141, 108, 38, 160, 46], OperandSize::Dword, ) } #[test] fn vcvtps2uqq_3() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(XMM8)), operand2: Some(Direct(XMM27)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast: None, }, &[98, 17, 125, 142, 121, 195], OperandSize::Qword, ) } #[test] fn vcvtps2uqq_4() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(XMM7)), operand2: Some(IndirectScaledIndexed( RDI, RSI, Two, Some(OperandSize::Qword), None, )), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K1), broadcast: None, }, &[98, 241, 125, 137, 121, 60, 119], OperandSize::Qword, ) } #[test] fn vcvtps2uqq_5() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(YMM4)), operand2: Some(Direct(XMM6)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None, }, &[98, 241, 125, 171, 121, 230], OperandSize::Dword, ) } #[test] fn vcvtps2uqq_6() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(YMM0)), operand2: Some(IndirectScaledDisplaced( ESI, Four, 1742127559, Some(OperandSize::Xmmword), None, )), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None, }, &[98, 241, 125, 170, 121, 4, 181, 199, 193, 214, 103], OperandSize::Dword, ) } #[test] fn vcvtps2uqq_7() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(YMM12)), operand2: Some(Direct(XMM24)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None, }, &[98, 17, 125, 171, 121, 224], OperandSize::Qword, ) } #[test] fn vcvtps2uqq_8() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(YMM21)), operand2: Some(IndirectScaledDisplaced( RAX, Eight, 796565832, Some(OperandSize::Xmmword), None, )), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K5), broadcast: None, }, &[98, 225, 125, 173, 121, 44, 197, 72, 161, 122, 47], OperandSize::Qword, ) } #[test] fn vcvtps2uqq_9() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(ZMM0)), operand2: Some(Direct(YMM5)), operand3: None, operand4: None, lock: false, rounding_mode: Some(RoundingMode::Zero), merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None, }, &[98, 241, 125, 251, 121, 197], OperandSize::Dword, ) } #[test] fn vcvtps2uqq_10() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(ZMM5)), operand2: Some(IndirectDisplaced( EAX, 1019708652, Some(OperandSize::Ymmword), None, )), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None, }, &[98, 241, 125, 202, 121, 168, 236, 132, 199, 60], OperandSize::Dword, ) } #[test] fn vcvtps2uqq_11() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(ZMM27)), operand2: Some(Direct(YMM21)), operand3: None, operand4: None, lock: false, rounding_mode: Some(RoundingMode::Nearest), merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast: None, }, &[98, 33, 125, 158, 121, 221], OperandSize::Qword, ) } #[test] fn vcvtps2uqq_12() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(ZMM25)), operand2: Some(IndirectDisplaced( RDI, 1515537008, Some(OperandSize::Ymmword), None, )), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None, }, &[98, 97, 125, 203, 121, 143, 112, 66, 85, 90], OperandSize::Qword, ) }
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vcvtps2uqq_1() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM4)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K5), broadcast: None, }, &[98, 241, 125, 141, 121, 212], OperandSize::Dword, ) } #[test] fn vcvtps2uqq_2() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledDisplaced( ECX, Four, 782247532, Some(OperandSize::Qword), None, )), operand3: None, operand4: Non
nic::VCVTPS2UQQ, operand1: Some(Direct(ZMM25)), operand2: Some(IndirectDisplaced( RDI, 1515537008, Some(OperandSize::Ymmword), None, )), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None, }, &[98, 97, 125, 203, 121, 143, 112, 66, 85, 90], OperandSize::Qword, ) }
e, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), broadcast: None, }, &[98, 241, 125, 143, 121, 52, 141, 108, 38, 160, 46], OperandSize::Dword, ) } #[test] fn vcvtps2uqq_3() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(XMM8)), operand2: Some(Direct(XMM27)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast: None, }, &[98, 17, 125, 142, 121, 195], OperandSize::Qword, ) } #[test] fn vcvtps2uqq_4() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(XMM7)), operand2: Some(IndirectScaledIndexed( RDI, RSI, Two, Some(OperandSize::Qword), None, )), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K1), broadcast: None, }, &[98, 241, 125, 137, 121, 60, 119], OperandSize::Qword, ) } #[test] fn vcvtps2uqq_5() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(YMM4)), operand2: Some(Direct(XMM6)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None, }, &[98, 241, 125, 171, 121, 230], OperandSize::Dword, ) } #[test] fn vcvtps2uqq_6() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(YMM0)), operand2: Some(IndirectScaledDisplaced( ESI, Four, 1742127559, Some(OperandSize::Xmmword), None, )), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None, }, &[98, 241, 125, 170, 121, 4, 181, 199, 193, 214, 103], OperandSize::Dword, ) } #[test] fn vcvtps2uqq_7() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(YMM12)), operand2: Some(Direct(XMM24)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None, }, &[98, 17, 125, 171, 121, 224], OperandSize::Qword, ) } #[test] fn vcvtps2uqq_8() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(YMM21)), operand2: Some(IndirectScaledDisplaced( RAX, Eight, 796565832, Some(OperandSize::Xmmword), None, )), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K5), broadcast: None, }, &[98, 225, 125, 173, 121, 44, 197, 72, 161, 122, 47], OperandSize::Qword, ) } #[test] fn vcvtps2uqq_9() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(ZMM0)), operand2: Some(Direct(YMM5)), operand3: None, operand4: None, lock: false, rounding_mode: Some(RoundingMode::Zero), merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None, }, &[98, 241, 125, 251, 121, 197], OperandSize::Dword, ) } #[test] fn vcvtps2uqq_10() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(ZMM5)), operand2: Some(IndirectDisplaced( EAX, 1019708652, Some(OperandSize::Ymmword), None, )), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None, }, &[98, 241, 125, 202, 121, 168, 236, 132, 199, 60], OperandSize::Dword, ) } #[test] fn vcvtps2uqq_11() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(ZMM27)), operand2: Some(Direct(YMM21)), operand3: None, operand4: None, lock: false, rounding_mode: Some(RoundingMode::Nearest), merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast: None, }, &[98, 33, 125, 158, 121, 221], OperandSize::Qword, ) } #[test] fn vcvtps2uqq_12() { run_test( &Instruction { mnemonic: Mnemo
random
[ { "content": "fn encode64_helper2(mnemonic: Mnemonic, operand1: Operand, operand2: Operand, expected: &Vec<u8>) {\n\n let instr = Instruction {\n\n mnemonic: mnemonic,\n\n operand1: Some(operand1),\n\n operand2: Some(operand2),\n\n operand3: None,\n\n operand4: None,\n\n ...
Rust
verify/src/span.rs
tamasfe/verify
5f12650c5aef0edb63961042f7bc7b8da3644cea
use std::ops::{Add, AddAssign}; pub trait Span: core::fmt::Debug + Clone + core::ops::AddAssign {} pub trait SpanExt: Sized + Clone { fn combine(&mut self, span: Self); fn combined(&self, span: Self) -> Self { let mut new = self.clone(); new.combine(span); new } } impl<S: Span> SpanExt for S { fn combine(&mut self, span: Self) { *self += span; } } impl<S: Span> SpanExt for Option<S> { fn combine(&mut self, span: Self) { match span { Some(new_span) => match self { Some(s) => *s += new_span, None => *self = Some(new_span), }, None => { *self = None; } } } } pub trait Spanned { type Span: Span; fn span(&self) -> Option<Self::Span>; } #[cfg(feature = "smallvec")] type KeysSmallVecArray = [String; 10]; #[cfg(feature = "smallvec")] type KeysInner = smallvec_crate::SmallVec<KeysSmallVecArray>; #[cfg(not(feature = "smallvec"))] type KeysInner = Vec<String>; #[derive(Debug, Default, Clone, Eq, PartialEq)] #[repr(transparent)] pub struct Keys(KeysInner); impl Span for Keys {} impl Keys { pub fn new() -> Self { Keys(KeysInner::new()) } pub fn with_capacity(cap: usize) -> Self { Keys(KeysInner::with_capacity(cap)) } pub fn iter(&self) -> impl Iterator<Item = &String> { self.0.iter() } pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut String> { self.0.iter_mut() } pub fn dotted(&self) -> String { self.0.join(".") } pub fn push(&mut self, value: String) { self.0.push(value) } pub fn into_inner(self) -> KeysInner { self.0 } } impl AddAssign for Keys { fn add_assign(&mut self, rhs: Self) { self.0.extend(rhs.0.into_iter()) } } impl<S: ToString> Add<S> for Keys { type Output = Self; fn add(mut self, rhs: S) -> Self::Output { self.push(rhs.to_string()); self } } impl From<String> for Keys { fn from(s: String) -> Self { let mut v = Self::new(); v.push(s); v } } impl IntoIterator for Keys { type Item = <KeysInner as IntoIterator>::Item; #[cfg(feature = "smallvec")] type IntoIter = smallvec_crate::IntoIter<KeysSmallVecArray>; #[cfg(not(feature = "smallvec"))] type IntoIter = std::vec::IntoIter<String>; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } }
use std::ops::{Add, AddAssign}; pub trait Span: core::fmt::Debug + Clone + core::ops::AddAssign {} pub trait SpanExt: Sized + Clone { fn combine(&mut self, span: Self); fn combined(&self, span: Self) -> Self { let mut new = self.clone(); new.combine(span); new } } impl<S: Span> SpanExt for S { fn combine(&mut self, span: Self) { *self += span; } } impl<S: Span> SpanExt for Option<S> {
} pub trait Spanned { type Span: Span; fn span(&self) -> Option<Self::Span>; } #[cfg(feature = "smallvec")] type KeysSmallVecArray = [String; 10]; #[cfg(feature = "smallvec")] type KeysInner = smallvec_crate::SmallVec<KeysSmallVecArray>; #[cfg(not(feature = "smallvec"))] type KeysInner = Vec<String>; #[derive(Debug, Default, Clone, Eq, PartialEq)] #[repr(transparent)] pub struct Keys(KeysInner); impl Span for Keys {} impl Keys { pub fn new() -> Self { Keys(KeysInner::new()) } pub fn with_capacity(cap: usize) -> Self { Keys(KeysInner::with_capacity(cap)) } pub fn iter(&self) -> impl Iterator<Item = &String> { self.0.iter() } pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut String> { self.0.iter_mut() } pub fn dotted(&self) -> String { self.0.join(".") } pub fn push(&mut self, value: String) { self.0.push(value) } pub fn into_inner(self) -> KeysInner { self.0 } } impl AddAssign for Keys { fn add_assign(&mut self, rhs: Self) { self.0.extend(rhs.0.into_iter()) } } impl<S: ToString> Add<S> for Keys { type Output = Self; fn add(mut self, rhs: S) -> Self::Output { self.push(rhs.to_string()); self } } impl From<String> for Keys { fn from(s: String) -> Self { let mut v = Self::new(); v.push(s); v } } impl IntoIterator for Keys { type Item = <KeysInner as IntoIterator>::Item; #[cfg(feature = "smallvec")] type IntoIter = smallvec_crate::IntoIter<KeysSmallVecArray>; #[cfg(not(feature = "smallvec"))] type IntoIter = std::vec::IntoIter<String>; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } }
fn combine(&mut self, span: Self) { match span { Some(new_span) => match self { Some(s) => *s += new_span, None => *self = Some(new_span), }, None => { *self = None; } } }
function_block-full_function
[ { "content": "/// Spans is used to provide spans for values that implement Serde Serialize.\n\n///\n\n/// Span hierarchy is controlled by the validators, only the new spans are required.\n\npub trait Spans: Clone + Default {\n\n /// The span type that is associated with each value.\n\n type Span: Span;\n\...
Rust
plonky2/src/gates/interpolation.rs
mfaulk/plonky2
2cedd1b02a718d19115560647ba1f741eab83260
use std::marker::PhantomData; use std::ops::Range; use plonky2_field::extension_field::algebra::PolynomialCoeffsAlgebra; use plonky2_field::extension_field::{Extendable, FieldExtension}; use plonky2_field::interpolation::interpolant; use plonky2_field::polynomial::PolynomialCoeffs; use crate::gadgets::interpolation::InterpolationGate; use crate::gadgets::polynomial::PolynomialCoeffsExtAlgebraTarget; use crate::gates::gate::Gate; use crate::gates::util::StridedConstraintConsumer; use crate::hash::hash_types::RichField; use crate::iop::ext_target::ExtensionTarget; use crate::iop::generator::{GeneratedValues, SimpleGenerator, WitnessGenerator}; use crate::iop::target::Target; use crate::iop::wire::Wire; use crate::iop::witness::{PartitionWitness, Witness}; use crate::plonk::circuit_builder::CircuitBuilder; use crate::plonk::vars::{EvaluationTargets, EvaluationVars, EvaluationVarsBase}; #[derive(Copy, Clone, Debug)] pub(crate) struct HighDegreeInterpolationGate<F: RichField + Extendable<D>, const D: usize> { pub subgroup_bits: usize, _phantom: PhantomData<F>, } impl<F: RichField + Extendable<D>, const D: usize> InterpolationGate<F, D> for HighDegreeInterpolationGate<F, D> { fn new(subgroup_bits: usize) -> Self { Self { subgroup_bits, _phantom: PhantomData, } } fn num_points(&self) -> usize { 1 << self.subgroup_bits } } impl<F: RichField + Extendable<D>, const D: usize> HighDegreeInterpolationGate<F, D> { fn end(&self) -> usize { self.start_coeffs() + self.num_points() * D } fn coset(&self, shift: F) -> impl Iterator<Item = F> { let g = F::primitive_root_of_unity(self.subgroup_bits); let size = 1 << self.subgroup_bits; g.powers().take(size).map(move |x| x * shift) } fn coset_ext(&self, shift: F::Extension) -> impl Iterator<Item = F::Extension> { let g = F::primitive_root_of_unity(self.subgroup_bits); let size = 1 << self.subgroup_bits; g.powers().take(size).map(move |x| shift.scalar_mul(x)) } fn coset_ext_recursive( &self, builder: &mut CircuitBuilder<F, D>, shift: ExtensionTarget<D>, ) -> Vec<ExtensionTarget<D>> { let g = F::primitive_root_of_unity(self.subgroup_bits); let size = 1 << self.subgroup_bits; g.powers() .take(size) .map(move |x| { let subgroup_element = builder.constant(x); builder.scalar_mul_ext(subgroup_element, shift) }) .collect() } } impl<F: RichField + Extendable<D>, const D: usize> Gate<F, D> for HighDegreeInterpolationGate<F, D> { fn id(&self) -> String { format!("{:?}<D={}>", self, D) } fn eval_unfiltered(&self, vars: EvaluationVars<F, D>) -> Vec<F::Extension> { let mut constraints = Vec::with_capacity(self.num_constraints()); let coeffs = (0..self.num_points()) .map(|i| vars.get_local_ext_algebra(self.wires_coeff(i))) .collect(); let interpolant = PolynomialCoeffsAlgebra::new(coeffs); let coset = self.coset_ext(vars.local_wires[self.wire_shift()]); for (i, point) in coset.into_iter().enumerate() { let value = vars.get_local_ext_algebra(self.wires_value(i)); let computed_value = interpolant.eval_base(point); constraints.extend(&(value - computed_value).to_basefield_array()); } let evaluation_point = vars.get_local_ext_algebra(self.wires_evaluation_point()); let evaluation_value = vars.get_local_ext_algebra(self.wires_evaluation_value()); let computed_evaluation_value = interpolant.eval(evaluation_point); constraints.extend(&(evaluation_value - computed_evaluation_value).to_basefield_array()); constraints } fn eval_unfiltered_base_one( &self, vars: EvaluationVarsBase<F>, mut yield_constr: StridedConstraintConsumer<F>, ) { let coeffs = (0..self.num_points()) .map(|i| vars.get_local_ext(self.wires_coeff(i))) .collect(); let interpolant = PolynomialCoeffs::new(coeffs); let coset = self.coset(vars.local_wires[self.wire_shift()]); for (i, point) in coset.into_iter().enumerate() { let value = vars.get_local_ext(self.wires_value(i)); let computed_value = interpolant.eval_base(point); yield_constr.many((value - computed_value).to_basefield_array()); } let evaluation_point = vars.get_local_ext(self.wires_evaluation_point()); let evaluation_value = vars.get_local_ext(self.wires_evaluation_value()); let computed_evaluation_value = interpolant.eval(evaluation_point); yield_constr.many((evaluation_value - computed_evaluation_value).to_basefield_array()); } fn eval_unfiltered_recursively( &self, builder: &mut CircuitBuilder<F, D>, vars: EvaluationTargets<D>, ) -> Vec<ExtensionTarget<D>> { let mut constraints = Vec::with_capacity(self.num_constraints()); let coeffs = (0..self.num_points()) .map(|i| vars.get_local_ext_algebra(self.wires_coeff(i))) .collect(); let interpolant = PolynomialCoeffsExtAlgebraTarget(coeffs); let coset = self.coset_ext_recursive(builder, vars.local_wires[self.wire_shift()]); for (i, point) in coset.into_iter().enumerate() { let value = vars.get_local_ext_algebra(self.wires_value(i)); let computed_value = interpolant.eval_scalar(builder, point); constraints.extend( &builder .sub_ext_algebra(value, computed_value) .to_ext_target_array(), ); } let evaluation_point = vars.get_local_ext_algebra(self.wires_evaluation_point()); let evaluation_value = vars.get_local_ext_algebra(self.wires_evaluation_value()); let computed_evaluation_value = interpolant.eval(builder, evaluation_point); constraints.extend( &builder .sub_ext_algebra(evaluation_value, computed_evaluation_value) .to_ext_target_array(), ); constraints } fn generators( &self, gate_index: usize, _local_constants: &[F], ) -> Vec<Box<dyn WitnessGenerator<F>>> { let gen = InterpolationGenerator::<F, D> { gate_index, gate: *self, _phantom: PhantomData, }; vec![Box::new(gen.adapter())] } fn num_wires(&self) -> usize { self.end() } fn num_constants(&self) -> usize { 0 } fn degree(&self) -> usize { self.num_points() } fn num_constraints(&self) -> usize { self.num_points() * D + D } } #[derive(Debug)] struct InterpolationGenerator<F: RichField + Extendable<D>, const D: usize> { gate_index: usize, gate: HighDegreeInterpolationGate<F, D>, _phantom: PhantomData<F>, } impl<F: RichField + Extendable<D>, const D: usize> SimpleGenerator<F> for InterpolationGenerator<F, D> { fn dependencies(&self) -> Vec<Target> { let local_target = |input| { Target::Wire(Wire { gate: self.gate_index, input, }) }; let local_targets = |inputs: Range<usize>| inputs.map(local_target); let num_points = self.gate.num_points(); let mut deps = Vec::with_capacity(1 + D + num_points * D); deps.push(local_target(self.gate.wire_shift())); deps.extend(local_targets(self.gate.wires_evaluation_point())); for i in 0..num_points { deps.extend(local_targets(self.gate.wires_value(i))); } deps } fn run_once(&self, witness: &PartitionWitness<F>, out_buffer: &mut GeneratedValues<F>) { let local_wire = |input| Wire { gate: self.gate_index, input, }; let get_local_wire = |input| witness.get_wire(local_wire(input)); let get_local_ext = |wire_range: Range<usize>| { debug_assert_eq!(wire_range.len(), D); let values = wire_range.map(get_local_wire).collect::<Vec<_>>(); let arr = values.try_into().unwrap(); F::Extension::from_basefield_array(arr) }; let points = self.gate.coset(get_local_wire(self.gate.wire_shift())); let points = points .into_iter() .enumerate() .map(|(i, point)| (point.into(), get_local_ext(self.gate.wires_value(i)))) .collect::<Vec<_>>(); let interpolant = interpolant(&points); for (i, &coeff) in interpolant.coeffs.iter().enumerate() { let wires = self.gate.wires_coeff(i).map(local_wire); out_buffer.set_ext_wires(wires, coeff); } let evaluation_point = get_local_ext(self.gate.wires_evaluation_point()); let evaluation_value = interpolant.eval(evaluation_point); let evaluation_value_wires = self.gate.wires_evaluation_value().map(local_wire); out_buffer.set_ext_wires(evaluation_value_wires, evaluation_value); } } #[cfg(test)] mod tests { use std::marker::PhantomData; use anyhow::Result; use plonky2_field::field_types::Field; use plonky2_field::goldilocks_field::GoldilocksField; use plonky2_field::polynomial::PolynomialCoeffs; use crate::gadgets::interpolation::InterpolationGate; use crate::gates::gate::Gate; use crate::gates::gate_testing::{test_eval_fns, test_low_degree}; use crate::gates::interpolation::HighDegreeInterpolationGate; use crate::hash::hash_types::HashOut; use crate::plonk::config::{GenericConfig, PoseidonGoldilocksConfig}; use crate::plonk::vars::EvaluationVars; #[test] fn wire_indices() { let gate = HighDegreeInterpolationGate::<GoldilocksField, 4> { subgroup_bits: 1, _phantom: PhantomData, }; assert_eq!(gate.wire_shift(), 0); assert_eq!(gate.wires_value(0), 1..5); assert_eq!(gate.wires_value(1), 5..9); assert_eq!(gate.wires_evaluation_point(), 9..13); assert_eq!(gate.wires_evaluation_value(), 13..17); assert_eq!(gate.wires_coeff(0), 17..21); assert_eq!(gate.wires_coeff(1), 21..25); assert_eq!(gate.num_wires(), 25); } #[test] fn low_degree() { test_low_degree::<GoldilocksField, _, 4>(HighDegreeInterpolationGate::new(2)); } #[test] fn eval_fns() -> Result<()> { const D: usize = 2; type C = PoseidonGoldilocksConfig; type F = <C as GenericConfig<D>>::F; test_eval_fns::<F, C, _, D>(HighDegreeInterpolationGate::new(2)) } #[test] fn test_gate_constraint() { const D: usize = 2; type C = PoseidonGoldilocksConfig; type F = <C as GenericConfig<D>>::F; type FF = <C as GenericConfig<D>>::FE; fn get_wires( gate: &HighDegreeInterpolationGate<F, D>, shift: F, coeffs: PolynomialCoeffs<FF>, eval_point: FF, ) -> Vec<FF> { let points = gate.coset(shift); let mut v = vec![shift]; for x in points { v.extend(coeffs.eval(x.into()).0); } v.extend(eval_point.0); v.extend(coeffs.eval(eval_point).0); for i in 0..coeffs.len() { v.extend(coeffs.coeffs[i].0); } v.iter().map(|&x| x.into()).collect() } let shift = F::rand(); let coeffs = PolynomialCoeffs::new(vec![FF::rand(), FF::rand()]); let eval_point = FF::rand(); let gate = HighDegreeInterpolationGate::<F, D>::new(1); let vars = EvaluationVars { local_constants: &[], local_wires: &get_wires(&gate, shift, coeffs, eval_point), public_inputs_hash: &HashOut::rand(), }; assert!( gate.eval_unfiltered(vars).iter().all(|x| x.is_zero()), "Gate constraints are not satisfied." ); } }
use std::marker::PhantomData; use std::ops::Range; use plonky2_field::extension_field::algebra::PolynomialCoeffsAlgebra; use plonky2_field::extension_field::{Extendable, FieldExtension}; use plonky2_field::interpolation::interpolant; use plonky2_field::polynomial::PolynomialCoeffs; use crate::gadgets::interpolation::InterpolationGate; use crate::gadgets::polynomial::PolynomialCoeffsExtAlgebraTarget; use crate::gates::gate::Gate; use crate::gates::util::StridedConstraintConsumer; use crate::hash::hash_types::RichField; use crate::iop::ext_target::ExtensionTarget; use crate::iop::generator::{GeneratedValues, SimpleGenerator, WitnessGenerator}; use crate::iop::target::Target; use crate::iop::wire::Wire; use crate::iop::witness::{PartitionWitness, Witness}; use crate::plonk::circuit_builder::CircuitBuilder; use crate::plonk::vars::{EvaluationTargets, EvaluationVars, EvaluationVarsBase}; #[derive(Copy, Clone, Debug)] pub(crate) struct HighDegreeInterpolationGate<F: RichField + Extendable<D>, const D: usize> { pub subgroup_bits: usize, _phantom: PhantomData<F>, } impl<F: RichField + Extendable<D>, const D: usize> InterpolationGate<F, D> for HighDegreeInterpolationGate<F, D> { fn new(subgroup_bits: usize) -> Self { Self { subgroup_bits, _phantom: PhantomData, } } fn num_points(&self) -> usize { 1 << self.subgroup_bits } } impl<F: RichField + Extendable<D>, const D: usize> HighDegreeInterpolationGate<F, D> { fn end(&self) -> usize { self.start_coeffs() + self.num_points() * D } fn coset(&self, shift: F) -> impl Iterator<Item = F> { let g = F::primitive_root_of_unity(self.subgroup_bits); let size = 1 << self.subgroup_bits; g.powers().take(size).map(move |x| x * shift) } fn coset_ext(&self, shift: F::Extension) -> impl Iterator<Item = F::Extension> { let g = F::primitive_root_of_unity(self.subgroup_bits); let size = 1 << self.subgroup_bits; g.powers().take(size).map(move |x| shift.scalar_mul(x)) } fn coset_ext_recursive( &self, builder: &mut CircuitBuilder<F, D>, shift: ExtensionTarget<D>, ) -> Vec<ExtensionTarget<D>> { let g = F::primitive_root_of_unity(self.subgroup_bits); let size = 1 << self.subgroup_bits; g.powers() .take(size) .map(move |x| { let subgroup_element = builder.constant(x); builder.scalar_mul_ext(subgroup_element, shift) }) .collect() } } impl<F: RichField + Extendable<D>, const D: usize> Gate<F, D> for HighDegreeInterpolationGate<F, D> { fn id(&self) -> String { format!("{:?}<D={}>", self, D) } fn eval_unfiltered(&self, vars: EvaluationVars<F, D>) -> Vec<F::Extension> {
fn eval_unfiltered_base_one( &self, vars: EvaluationVarsBase<F>, mut yield_constr: StridedConstraintConsumer<F>, ) { let coeffs = (0..self.num_points()) .map(|i| vars.get_local_ext(self.wires_coeff(i))) .collect(); let interpolant = PolynomialCoeffs::new(coeffs); let coset = self.coset(vars.local_wires[self.wire_shift()]); for (i, point) in coset.into_iter().enumerate() { let value = vars.get_local_ext(self.wires_value(i)); let computed_value = interpolant.eval_base(point); yield_constr.many((value - computed_value).to_basefield_array()); } let evaluation_point = vars.get_local_ext(self.wires_evaluation_point()); let evaluation_value = vars.get_local_ext(self.wires_evaluation_value()); let computed_evaluation_value = interpolant.eval(evaluation_point); yield_constr.many((evaluation_value - computed_evaluation_value).to_basefield_array()); } fn eval_unfiltered_recursively( &self, builder: &mut CircuitBuilder<F, D>, vars: EvaluationTargets<D>, ) -> Vec<ExtensionTarget<D>> { let mut constraints = Vec::with_capacity(self.num_constraints()); let coeffs = (0..self.num_points()) .map(|i| vars.get_local_ext_algebra(self.wires_coeff(i))) .collect(); let interpolant = PolynomialCoeffsExtAlgebraTarget(coeffs); let coset = self.coset_ext_recursive(builder, vars.local_wires[self.wire_shift()]); for (i, point) in coset.into_iter().enumerate() { let value = vars.get_local_ext_algebra(self.wires_value(i)); let computed_value = interpolant.eval_scalar(builder, point); constraints.extend( &builder .sub_ext_algebra(value, computed_value) .to_ext_target_array(), ); } let evaluation_point = vars.get_local_ext_algebra(self.wires_evaluation_point()); let evaluation_value = vars.get_local_ext_algebra(self.wires_evaluation_value()); let computed_evaluation_value = interpolant.eval(builder, evaluation_point); constraints.extend( &builder .sub_ext_algebra(evaluation_value, computed_evaluation_value) .to_ext_target_array(), ); constraints } fn generators( &self, gate_index: usize, _local_constants: &[F], ) -> Vec<Box<dyn WitnessGenerator<F>>> { let gen = InterpolationGenerator::<F, D> { gate_index, gate: *self, _phantom: PhantomData, }; vec![Box::new(gen.adapter())] } fn num_wires(&self) -> usize { self.end() } fn num_constants(&self) -> usize { 0 } fn degree(&self) -> usize { self.num_points() } fn num_constraints(&self) -> usize { self.num_points() * D + D } } #[derive(Debug)] struct InterpolationGenerator<F: RichField + Extendable<D>, const D: usize> { gate_index: usize, gate: HighDegreeInterpolationGate<F, D>, _phantom: PhantomData<F>, } impl<F: RichField + Extendable<D>, const D: usize> SimpleGenerator<F> for InterpolationGenerator<F, D> { fn dependencies(&self) -> Vec<Target> { let local_target = |input| { Target::Wire(Wire { gate: self.gate_index, input, }) }; let local_targets = |inputs: Range<usize>| inputs.map(local_target); let num_points = self.gate.num_points(); let mut deps = Vec::with_capacity(1 + D + num_points * D); deps.push(local_target(self.gate.wire_shift())); deps.extend(local_targets(self.gate.wires_evaluation_point())); for i in 0..num_points { deps.extend(local_targets(self.gate.wires_value(i))); } deps } fn run_once(&self, witness: &PartitionWitness<F>, out_buffer: &mut GeneratedValues<F>) { let local_wire = |input| Wire { gate: self.gate_index, input, }; let get_local_wire = |input| witness.get_wire(local_wire(input)); let get_local_ext = |wire_range: Range<usize>| { debug_assert_eq!(wire_range.len(), D); let values = wire_range.map(get_local_wire).collect::<Vec<_>>(); let arr = values.try_into().unwrap(); F::Extension::from_basefield_array(arr) }; let points = self.gate.coset(get_local_wire(self.gate.wire_shift())); let points = points .into_iter() .enumerate() .map(|(i, point)| (point.into(), get_local_ext(self.gate.wires_value(i)))) .collect::<Vec<_>>(); let interpolant = interpolant(&points); for (i, &coeff) in interpolant.coeffs.iter().enumerate() { let wires = self.gate.wires_coeff(i).map(local_wire); out_buffer.set_ext_wires(wires, coeff); } let evaluation_point = get_local_ext(self.gate.wires_evaluation_point()); let evaluation_value = interpolant.eval(evaluation_point); let evaluation_value_wires = self.gate.wires_evaluation_value().map(local_wire); out_buffer.set_ext_wires(evaluation_value_wires, evaluation_value); } } #[cfg(test)] mod tests { use std::marker::PhantomData; use anyhow::Result; use plonky2_field::field_types::Field; use plonky2_field::goldilocks_field::GoldilocksField; use plonky2_field::polynomial::PolynomialCoeffs; use crate::gadgets::interpolation::InterpolationGate; use crate::gates::gate::Gate; use crate::gates::gate_testing::{test_eval_fns, test_low_degree}; use crate::gates::interpolation::HighDegreeInterpolationGate; use crate::hash::hash_types::HashOut; use crate::plonk::config::{GenericConfig, PoseidonGoldilocksConfig}; use crate::plonk::vars::EvaluationVars; #[test] fn wire_indices() { let gate = HighDegreeInterpolationGate::<GoldilocksField, 4> { subgroup_bits: 1, _phantom: PhantomData, }; assert_eq!(gate.wire_shift(), 0); assert_eq!(gate.wires_value(0), 1..5); assert_eq!(gate.wires_value(1), 5..9); assert_eq!(gate.wires_evaluation_point(), 9..13); assert_eq!(gate.wires_evaluation_value(), 13..17); assert_eq!(gate.wires_coeff(0), 17..21); assert_eq!(gate.wires_coeff(1), 21..25); assert_eq!(gate.num_wires(), 25); } #[test] fn low_degree() { test_low_degree::<GoldilocksField, _, 4>(HighDegreeInterpolationGate::new(2)); } #[test] fn eval_fns() -> Result<()> { const D: usize = 2; type C = PoseidonGoldilocksConfig; type F = <C as GenericConfig<D>>::F; test_eval_fns::<F, C, _, D>(HighDegreeInterpolationGate::new(2)) } #[test] fn test_gate_constraint() { const D: usize = 2; type C = PoseidonGoldilocksConfig; type F = <C as GenericConfig<D>>::F; type FF = <C as GenericConfig<D>>::FE; fn get_wires( gate: &HighDegreeInterpolationGate<F, D>, shift: F, coeffs: PolynomialCoeffs<FF>, eval_point: FF, ) -> Vec<FF> { let points = gate.coset(shift); let mut v = vec![shift]; for x in points { v.extend(coeffs.eval(x.into()).0); } v.extend(eval_point.0); v.extend(coeffs.eval(eval_point).0); for i in 0..coeffs.len() { v.extend(coeffs.coeffs[i].0); } v.iter().map(|&x| x.into()).collect() } let shift = F::rand(); let coeffs = PolynomialCoeffs::new(vec![FF::rand(), FF::rand()]); let eval_point = FF::rand(); let gate = HighDegreeInterpolationGate::<F, D>::new(1); let vars = EvaluationVars { local_constants: &[], local_wires: &get_wires(&gate, shift, coeffs, eval_point), public_inputs_hash: &HashOut::rand(), }; assert!( gate.eval_unfiltered(vars).iter().all(|x| x.is_zero()), "Gate constraints are not satisfied." ); } }
let mut constraints = Vec::with_capacity(self.num_constraints()); let coeffs = (0..self.num_points()) .map(|i| vars.get_local_ext_algebra(self.wires_coeff(i))) .collect(); let interpolant = PolynomialCoeffsAlgebra::new(coeffs); let coset = self.coset_ext(vars.local_wires[self.wire_shift()]); for (i, point) in coset.into_iter().enumerate() { let value = vars.get_local_ext_algebra(self.wires_value(i)); let computed_value = interpolant.eval_base(point); constraints.extend(&(value - computed_value).to_basefield_array()); } let evaluation_point = vars.get_local_ext_algebra(self.wires_evaluation_point()); let evaluation_value = vars.get_local_ext_algebra(self.wires_evaluation_value()); let computed_evaluation_value = interpolant.eval(evaluation_point); constraints.extend(&(evaluation_value - computed_evaluation_value).to_basefield_array()); constraints }
function_block-function_prefix_line
[ { "content": "/// Tests that the constraints imposed by the given gate are low-degree by applying them to random\n\n/// low-degree witness polynomials.\n\npub fn test_low_degree<F: RichField + Extendable<D>, G: Gate<F, D>, const D: usize>(gate: G) {\n\n let rate_bits = log2_ceil(gate.degree() + 1);\n\n\n\n ...
Rust
tests/config_read_tests/configuration_tests.rs
szarykott/miau
a2ad16c2f205a21c1c35ffd91c08163b583c4d29
use miau::{ builder::ConfigurationBuilder, configuration::{Configuration, ConfigurationRead}, error::ErrorCode, format::Json, source::InMemorySource, }; use rstest::rstest; #[test] fn test_arrays_are_subsituted_when_config_is_built() { let json1 = r#"{"array1" : [1,2,3,4]}"#; let json2 = r#"{"array1" : [5,6]}"#; let json3 = r#"{"array1" : [7]}"#; let mut builder = ConfigurationBuilder::default(); builder .add(InMemorySource::from_string_slice(json1), Json::new()) .add(InMemorySource::from_string_slice(json2), Json::new()) .add(InMemorySource::from_string_slice(json3), Json::new()); let confiuration = builder.build().unwrap(); assert_eq!(Some(7), confiuration.get("array1:[0]")); assert_eq!(Some(6), confiuration.get("array1:[1]")); assert_eq!(Some(3), confiuration.get("array1:[2]")); assert_eq!(Some(4), confiuration.get("array1:[3]")); } #[test] fn test_array_to_map_substitution() { let json1 = r#"{"key" : [7]}"#; let json2 = r#"{"key" : { "key" : 7 }}"#; let mut builder = ConfigurationBuilder::default(); builder .add(InMemorySource::from_string_slice(json1), Json::new()) .add(InMemorySource::from_string_slice(json2), Json::new()); let configuration = builder.build().unwrap(); assert_eq!(Some(7), configuration.get("key:[0]")); assert_eq!(Some(7), configuration.get("key:key")); } #[test] fn test_map_to_array_substitution() { let json1 = r#"{"key" : { "key" : 7 }}"#; let json2 = r#"{"key" : [7]}"#; let mut builder = ConfigurationBuilder::default(); builder .add(InMemorySource::from_string_slice(json1), Json::new()) .add(InMemorySource::from_string_slice(json2), Json::new()); let configuration = builder.build().unwrap(); assert_eq!(Some(7), configuration.get("key:[0]")); assert_eq!(Some(7), configuration.get("key:key")); } #[rstest( c1, c2, exp, case(r#"{"value1" : 1}"#, r#"{"value1" : 2}"#, 2), case(r#"{"value1" : 1.2}"#, r#"{"value1" : 1}"#, 1), case(r#"{"value1" : false}"#, r#"{"value1" : 3}"#, 3), case(r#"{"value1" : "true"}"#, r#"{"value1" : -4}"#, -4) )] fn test_type_to_integer_substitution(c1: &str, c2: &str, exp: isize) { let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(c1), Json::new()); builder.add(InMemorySource::from_string_slice(c2), Json::new()); let result = builder.build(); assert!(result.is_ok()); let result = result.unwrap(); assert_eq!(Some(exp), result.get("value1")); } #[rstest( c1, c2, exp, case(r#"{"value1" : 1}"#, r#"{"value1" : 2.1}"#, 2.1f64), case(r#"{"value1" : 1.2}"#, r#"{"value1" : 1.1}"#, 1.1f64), case(r#"{"value1" : false}"#, r#"{"value1" : 3.1}"#, 3.1f64), case(r#"{"value1" : "true"}"#, r#"{"value1" : 4.1}"#, 4.1f64) )] fn test_type_to_float_substitution(c1: &str, c2: &str, exp: f64) { let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(c1), Json::new()); builder.add(InMemorySource::from_string_slice(c2), Json::new()); let result = builder.build().unwrap(); assert_eq!(Some(exp), result.get("value1")); } #[rstest( c1, c2, exp, case(r#"{"value1" : 1}"#, r#"{"value1" : true}"#, true), case(r#"{"value1" : 1.2}"#, r#"{"value1" : true}"#, true), case(r#"{"value1" : false}"#, r#"{"value1" : true}"#, true), case(r#"{"value1" : "true"}"#, r#"{"value1" : false}"#, false) )] fn test_type_to_bool_substitution(c1: &str, c2: &str, exp: bool) { let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(c1), Json::new()); builder.add(InMemorySource::from_string_slice(c2), Json::new()); let result = builder.build().unwrap(); assert_eq!(Some(exp), result.get("value1")); } #[rstest( c1, c2, exp, case(r#"{"value1" : 1}"#, r#"{"value1" : "true"}"#, "true"), case(r#"{"value1" : 1.2}"#, r#"{"value1" : "true"}"#, "true"), case(r#"{"value1" : false}"#, r#"{"value1" : "true"}"#, "true"), case(r#"{"value1" : "true"}"#, r#"{"value1" : "false"}"#, "false") )] fn test_type_to_string_substitution(c1: &str, c2: &str, exp: &str) { let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(c1), Json::new()); builder.add(InMemorySource::from_string_slice(c2), Json::new()); let result = builder.build().unwrap(); assert_eq!(Some(exp), result.get("value1")); } #[test] fn test_single_value_integer_config_build_json() { let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>("1").unwrap()) .add_provider(serde_json::from_str::<Configuration>("2").unwrap()) .build() .unwrap(); assert_eq!(Some(2i32), result.get("")); } #[test] fn test_single_map_entry_config_build_json() { let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(r#"{"value" : 1}"#).unwrap()) .add_provider(serde_json::from_str::<Configuration>(r#"{"value" : 2}"#).unwrap()) .build() .unwrap(); assert_eq!(Some(2), result.get("value")); } #[test] fn test_single_map_entry_config_build_json_different_type() { let config_str_1 = r#"{"value" : 1}"#; let config_str_2 = r#"{"value" : "2"}"#; let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some("2"), result.get("value")); assert_eq!(Some(2), result.get("value")); } #[test] fn test_two_different_map_entries_config_build_json() { let config_str_1 = r#"{"value1" : 1}"#; let config_str_2 = r#"{"value2" : 2}"#; let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some(1), result.get("value1")); assert_eq!(Some(2), result.get("value2")); } #[test] fn test_single_array_entry_config_build_json() { let config_str_1 = r#"[1]"#; let config_str_2 = r#"[2]"#; let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some(2), result.get("[0]")); } #[test] fn test_complex_map_config_build_json() { let config_str_1 = r#" { "firstName": "John", "lastName": "Smith", "isAlive": true, "address": { "streetAddress": "21 2nd Street" }, "phoneNumbers": [ { "type": "home", "number": "212 555-1234" } ], "spouse": null } "# .trim(); let config_str_2 = r#" { "firstName": "Andrew", "isAlive": false, "address": { "streetAddress": "Knowhere" }, "phoneNumbers": [ { "type": "work", "number": "212 555-1234" } ], "spouse": true } "# .trim(); let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some("Andrew"), result.get("firstName")); assert_eq!(Some("Smith"), result.get("lastName")); assert_eq!(Some(false), result.get("isAlive")); assert_eq!(Some("Knowhere"), result.get("address:streetAddress")); assert_eq!(Some("work"), result.get("phoneNumbers:[0]:type")); assert_eq!(Some(true), result.get("spouse")); } #[test] fn test_array_of_structs_build_json() { let config_str_1 = r#" { "array" : [ { "v" : 1, "k" : 11 }, { "v" : 3, "k" : 33 } ] } "# .trim(); let config_str_2 = r#" { "array": [ { "v" : 1, "k" : 12 } ] } "# .trim(); let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some(12), result.get("array:[0]:k")); assert_eq!(Some(33), result.get("array:[1]:k")); } #[test] fn test_structs_of_arrays_build_json() { let config_str_1 = r#" { "structure" : { "a1" : [1, 42, 3], "a2" : [1, 2] } } "# .trim(); let config_str_2 = r#" { "structure" : { "a1" : [11], "a2" : [4, 5, 3] } } "# .trim(); let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some(11), result.get("structure:a1:[0]")); assert_eq!(Some(42), result.get("structure:a1:[1]")); assert_eq!(Some(3), result.get("structure:a1:[2]")); assert_eq!( None, ConfigurationRead::<'_, i32, &str>::get(&result, "structure:a1:[3]") ); assert_eq!(Some(4), result.get("structure:a2:[0]")); assert_eq!(Some(5), result.get("structure:a2:[1]")); assert_eq!(Some(3), result.get("structure:a2:[2]")); assert_eq!( None, ConfigurationRead::<'_, i32, &str>::get(&result, "structure:a2:[3]") ); } #[test] fn test_triple_nested_map_build() { let config_str_1 = r#" { "key1" : { "key2" : { "key3" : true, "key4" : false } } } "# .trim(); let config_str_2 = r#" { "key1" : { "key2" : { "key3" : false } } } "# .trim(); let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some(false), result.get("key1:key2:key3")); assert_eq!(Some(false), result.get("key1:key2:key4")); assert_eq!( None, ConfigurationRead::<'_, i32, &str>::get(&result, "key1:key2:key5") ); } #[test] fn test_get_result_non_existing_key() { let json1 = r#"{"key" : { "key" : 7 }}"#; let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(json1), Json::new()); let configuration = builder.build().unwrap(); let value = ConfigurationRead::<'_, i32, &str>::get_result(&configuration, "value").unwrap(); assert_eq!(None, value); } #[test] fn test_get_result_wrong_key_type() { let json1 = r#"{"key" : { "key" : "not_a_number" }}"#; let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(json1), Json::new()); let configuration = builder.build().unwrap(); let value = ConfigurationRead::<'_, i32, &str>::get_result(&configuration, "key:key").unwrap(); assert_eq!(None, value); } #[test] fn test_get_result_key_unparsable() { let json1 = r#"{"key" : { "key" : "not_a_number" }}"#; let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(json1), Json::new()); let configuration = builder.build().unwrap(); let key = "key:[A]:key"; let error = ConfigurationRead::<'_, i32, &str>::get_result(&configuration, key).unwrap_err(); let error_string = error.to_string(); assert!(std::matches!(error.get_code(), ErrorCode::ParsingError(..))); assert!(error_string.contains(key)); }
use miau::{ builder::ConfigurationBuilder, configuration::{Configuration, ConfigurationRead}, error::ErrorCode, format::Json, source::InMemorySource, }; use rstest::rstest; #[test] fn test_arrays_are_subsituted_when_config_is_built() { let json1 = r#"{"array1" : [1,2,3,4]}"#; let json2 = r#"{"array1" : [5,6]}"#; let json3 = r#"{"array1" : [7]}"#; let mut builder = ConfigurationBuilder::default(); builder .add(InMemorySource::from_string_slice(json1), Json::new()) .add(InMemorySource::from_string_slice(json2), Json::new()) .add(InMemorySource::from_string_slice(json3), Json::new()); let confiuration = builder.build().unwrap(); assert_eq!(Some(7), confiuration.get("array1:[0]")); assert_eq!(Some(6), confiuration.get("array1:[1]")); assert_eq!(Some(3), confiuration.get("array1:[2]")); assert_eq!(Some(4), confiuration.get("array1:[3]")); } #[test] fn test_array_to_map_substitution() { let json1 = r#"{"key" : [7]}"#; let json2 = r#"{"key" : { "key" : 7 }}"#; let mut builder = ConfigurationBuilder::default(); builder .add(InMemorySource::from_string_slice(json1), Json::new()) .add(InMemorySource::from_string_slice(json2), Json::new()); let configuration = builder.build().unwrap(); assert_eq!(Some(7), configuration.get("key:[0]")); assert_eq!(Some(7), configuration.get("key:key")); } #[test] fn test_map_to_array_substitution() { let json1 = r#"{"key" : { "key" : 7 }}"#; let json2 = r#"{"key" : [7]}"#; let mut builder = ConfigurationBuilder::default(); builder .add(InMemorySource::from_string_slice(json1), Json::new()) .add(InMemorySource::from_string_slice(json2), Json::new()); let configuration = builder.build().unwrap(); assert_eq!(Some(7), configuration.get("key:[0]")); assert_eq!(Some(7), configuration.get("key:key")); } #[rstest( c1, c2, exp, case(r#"{"value1" : 1}"#, r#"{"value1" : 2}"#, 2), case(r#"{"value1" : 1.2}"#, r#"{"value1" : 1}"#, 1), case(r#"{"value1" : false}"#, r#"{"value1" : 3}"#, 3), case(r#"{"value1" : "true"}"#, r#"{"value1" : -4}"#, -4) )] fn test_type_to_integer_substitution(c1: &str, c2: &str, exp: isize) { let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(c1), Json::new()); builder.add(InMemorySource::from_string_slice(c2), Json::new()); let result = builder.build(); assert!(result.is_ok()); let result = result.unwrap(); assert_eq!(Some(exp), result.get("value1")); } #[rstest( c1, c2, exp, case(r#"{"value1" : 1}"#, r#"{"value1" : 2.1}"#, 2.1f64), case(r#"{"value1" : 1.2}"#, r#"{"value1" : 1.1}"#, 1.1f64), case(r#"{"value1" : false}"#, r#"{"value1" : 3.1}"#, 3.1f64), case(r#"{"value1" : "true"}"#, r#"{"value1" : 4.1}"#, 4.1f64) )] fn test_type_to_float_substitution(c1: &str, c2: &str, exp: f64) { let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(c1), Json::new()); builder.add(InMemorySource::from_string_slice(c2), Json::new()); let result = builder.build().unwrap(); assert_eq!(Some(exp), result.get("value1")); } #[rstest( c1, c2, exp, case(r#"{"value1" : 1}"#, r#"{"value1" : true}"#, true), case(r#"{"value1" : 1.2}"#, r#"{"value1" : true}"#, true), case(r#"{"value1" : false}"#, r#"{"value1" : true}"#, true), case(r#"{"value1" : "true"}"#, r#"{"value1" : false}"#, false) )] fn test_type_to_bool_substitution(c1: &str, c2: &str, exp: bool) { let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(c1), Json::new()); builder.add(InMemorySource::from_string_slice(c2), Json::new()); let result = builder.build().unwrap(); assert_eq!(Some(exp), result.get("value1")); } #[rstest( c1, c2, exp, case(r#"{"value1" : 1}"#, r#"{"value1" : "true"}"#, "true"), case(r#"{"value1" : 1.2}"#, r#"{"value1" : "true"}"#, "true"), case(r#"{"value1" : false}"#, r#"{"value1" : "true"}"#, "true"), case(r#"{"value1" : "true"}"#, r#"{"value1" : "false"}"#, "false") )] fn test_type_to_string_substitution(c1: &str, c2: &str, exp: &str) { let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(c1), Json::new()); builder.add(InMemorySource::from_string_slice(c2), Json::new()); let result = builder.build().unwrap(); assert_eq!(Some(exp), result.get("value1")); } #[test] fn test_single_value_integer_config_build_json() { let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>("1").unwrap()) .add_provider(serde_json::from_str::<Configuration>("2").unwrap()) .build() .unwrap(); assert_eq!(Some(2i32), result.get("")); } #[test] fn test_single_map_entry_config_build_json() { let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(r#"{"value" : 1}"#).unwrap()) .add_provider(serde_json::from_str::<Configuration>(r#"{"value" : 2}"#).unwrap()) .build() .unwrap(); assert_eq!(Some(2), result.get("value")); } #[test] fn test_single_map_entry_config_build_json_different_type() { let config_str_1 = r#"{"value" : 1}"#; let config_str_2 = r#"{"value" : "2"}"#; let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some("2"), result.get("value")); assert_eq!(Some(2), result.get("value")); } #[test] fn test_two_different_map_entries_config_build_json() { let config_str_1 = r#"{"value1" : 1}"#; let config_str_2 = r#"{"value2" : 2}"#; let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some(1), result.get("value1")); assert_eq!(Some(2), result.get("value2")); } #[test] fn test_single_array_entry_config_build_json() { let config_str_1 = r#"[1]"#; let config_str_2 = r#"[2]"#; let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::fro
#[test] fn test_complex_map_config_build_json() { let config_str_1 = r#" { "firstName": "John", "lastName": "Smith", "isAlive": true, "address": { "streetAddress": "21 2nd Street" }, "phoneNumbers": [ { "type": "home", "number": "212 555-1234" } ], "spouse": null } "# .trim(); let config_str_2 = r#" { "firstName": "Andrew", "isAlive": false, "address": { "streetAddress": "Knowhere" }, "phoneNumbers": [ { "type": "work", "number": "212 555-1234" } ], "spouse": true } "# .trim(); let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some("Andrew"), result.get("firstName")); assert_eq!(Some("Smith"), result.get("lastName")); assert_eq!(Some(false), result.get("isAlive")); assert_eq!(Some("Knowhere"), result.get("address:streetAddress")); assert_eq!(Some("work"), result.get("phoneNumbers:[0]:type")); assert_eq!(Some(true), result.get("spouse")); } #[test] fn test_array_of_structs_build_json() { let config_str_1 = r#" { "array" : [ { "v" : 1, "k" : 11 }, { "v" : 3, "k" : 33 } ] } "# .trim(); let config_str_2 = r#" { "array": [ { "v" : 1, "k" : 12 } ] } "# .trim(); let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some(12), result.get("array:[0]:k")); assert_eq!(Some(33), result.get("array:[1]:k")); } #[test] fn test_structs_of_arrays_build_json() { let config_str_1 = r#" { "structure" : { "a1" : [1, 42, 3], "a2" : [1, 2] } } "# .trim(); let config_str_2 = r#" { "structure" : { "a1" : [11], "a2" : [4, 5, 3] } } "# .trim(); let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some(11), result.get("structure:a1:[0]")); assert_eq!(Some(42), result.get("structure:a1:[1]")); assert_eq!(Some(3), result.get("structure:a1:[2]")); assert_eq!( None, ConfigurationRead::<'_, i32, &str>::get(&result, "structure:a1:[3]") ); assert_eq!(Some(4), result.get("structure:a2:[0]")); assert_eq!(Some(5), result.get("structure:a2:[1]")); assert_eq!(Some(3), result.get("structure:a2:[2]")); assert_eq!( None, ConfigurationRead::<'_, i32, &str>::get(&result, "structure:a2:[3]") ); } #[test] fn test_triple_nested_map_build() { let config_str_1 = r#" { "key1" : { "key2" : { "key3" : true, "key4" : false } } } "# .trim(); let config_str_2 = r#" { "key1" : { "key2" : { "key3" : false } } } "# .trim(); let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some(false), result.get("key1:key2:key3")); assert_eq!(Some(false), result.get("key1:key2:key4")); assert_eq!( None, ConfigurationRead::<'_, i32, &str>::get(&result, "key1:key2:key5") ); } #[test] fn test_get_result_non_existing_key() { let json1 = r#"{"key" : { "key" : 7 }}"#; let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(json1), Json::new()); let configuration = builder.build().unwrap(); let value = ConfigurationRead::<'_, i32, &str>::get_result(&configuration, "value").unwrap(); assert_eq!(None, value); } #[test] fn test_get_result_wrong_key_type() { let json1 = r#"{"key" : { "key" : "not_a_number" }}"#; let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(json1), Json::new()); let configuration = builder.build().unwrap(); let value = ConfigurationRead::<'_, i32, &str>::get_result(&configuration, "key:key").unwrap(); assert_eq!(None, value); } #[test] fn test_get_result_key_unparsable() { let json1 = r#"{"key" : { "key" : "not_a_number" }}"#; let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(json1), Json::new()); let configuration = builder.build().unwrap(); let key = "key:[A]:key"; let error = ConfigurationRead::<'_, i32, &str>::get_result(&configuration, key).unwrap_err(); let error_string = error.to_string(); assert!(std::matches!(error.get_code(), ErrorCode::ParsingError(..))); assert!(error_string.contains(key)); }
m_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some(2), result.get("[0]")); }
function_block-function_prefixed
[ { "content": "fn test_arrays_are_merged_when_substituted(json1: &str, json2: &str, exp: Vec<i32>) {\n\n let mut builder = ConfigurationBuilder::default();\n\n\n\n builder.add(\n\n InMemorySource::from_string_slice(json1.as_ref()),\n\n Json::new(),\n\n );\n\n builder.add(\n\n InM...
Rust
src/logger.rs
dignifiedquire/rust-drand
57cd6bcb459fb3fca1deb11c5a789c413ee308e2
use std::cmp::max; use std::io::{stderr, stdout, Write}; use std::sync::atomic::{AtomicUsize, Ordering}; use ansi_term::{ANSIGenericString, Colour, Style}; use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError}; use unicode_segmentation::UnicodeSegmentation; #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub enum Destination { Stdout, Stderr, } impl Destination { pub fn isatty(&self) -> bool { match *self { Destination::Stdout => atty::is(atty::Stream::Stdout), Destination::Stderr => atty::is(atty::Stream::Stderr), } } } impl Destination { fn write(&self) -> Box<dyn Write> { match *self { Destination::Stdout => Box::new(stdout()), Destination::Stderr => Box::new(stderr()), } } } impl Default for Destination { fn default() -> Destination { Destination::Stderr } } pub struct Logger { destination: Destination, level: LevelFilter, max_module_width: AtomicUsize, max_target_width: AtomicUsize, theme: Theme, } impl Logger { pub fn new(destination: Destination, level: LevelFilter, theme: Theme) -> Logger { Logger { destination, level, max_module_width: AtomicUsize::new(0), max_target_width: AtomicUsize::new(0), theme, } } pub fn set_logger(self) -> Result<(), SetLoggerError> { let level = self.level; log::set_boxed_logger(Box::new(self)).map(|()| log::set_max_level(level)) } fn update_module_width(&self, width: usize) -> usize { loop { let old = self.max_module_width.load(Ordering::SeqCst); let new = max(old, width); if self .max_module_width .compare_and_swap(old, new, Ordering::SeqCst) == old { return new; } } } fn update_target_width(&self, width: usize) -> usize { loop { let old = self.max_target_width.load(Ordering::SeqCst); let new = max(old, width); if self .max_target_width .compare_and_swap(old, new, Ordering::SeqCst) == old { return new; } } } } impl Default for Logger { fn default() -> Logger { let destination = Destination::default(); let theme = if destination.isatty() { Theme::default() } else { Theme::empty() }; Logger::new(destination, LevelFilter::Info, theme) } } impl Log for Logger { fn enabled(&self, metadata: &Metadata) -> bool { self.level .to_level() .map(|level| metadata.level() <= level) .unwrap_or(false) } fn flush(&self) {} fn log(&self, record: &Record) { if !self.enabled(record.metadata()) { return; } let module = record.module_path().unwrap_or("<unknown>"); let target = record.target(); let module_length = self.update_module_width(module.graphemes(true).count()); let _ = if module == target { writeln!( self.destination.write(), "{}|{:.*}| {}", self.theme.paint_log_level(record.level()), module_length, module, record.args() ) } else { let target_length = self.update_target_width(target.graphemes(true).count()); writeln!( self.destination.write(), "{}|{:.*}|{:.*}|{}", self.theme.paint_log_level(record.level()), module_length, module, target_length, target, record.args() ) }; } } #[derive(Clone, Copy, Debug, PartialEq)] pub struct Theme { pub error: Style, pub warn: Style, pub info: Style, pub debug: Style, pub trace: Style, pub module: Style, } impl Theme { pub fn empty() -> Theme { Theme { error: Style::new(), warn: Style::new(), info: Style::new(), debug: Style::new(), trace: Style::new(), module: Style::new(), } } pub fn paint_log_level(&self, level: Level) -> ANSIGenericString<'static, str> { let (style, name) = match level { Level::Error => (self.error, "😡 E "), Level::Warn => (self.warn, "😥 W "), Level::Info => (self.info, "😋 I "), Level::Debug => (self.debug, "🤔 D "), Level::Trace => (self.trace, "🤓 T "), }; style.paint(name) } } impl Default for Theme { fn default() -> Theme { Theme { error: Colour::Red.bold(), warn: Colour::Yellow.bold(), info: Colour::Cyan.normal(), debug: Colour::White.normal(), trace: Colour::White.dimmed(), module: Style::new(), } } } pub fn init( destination: Destination, level: LevelFilter, theme: Theme, ) -> Result<(), SetLoggerError> { platform_init(); Logger::new(destination, level, theme).set_logger() } pub fn init_level(level: LevelFilter) -> Result<(), SetLoggerError> { platform_init(); let mut logger = Logger::default(); logger.level = level; logger.set_logger() } pub fn init_to_defaults() -> Result<(), SetLoggerError> { platform_init(); Logger::default().set_logger() } #[cfg(windows)] fn platform_init() { use ansi_term::enable_ansi_support; let _ = enable_ansi_support(); } #[cfg(not(windows))] fn platform_init() {}
use std::cmp::max; use std::io::{stderr, stdout, Write}; use std::sync::atomic::{AtomicUsize, Ordering}; use ansi_term::{ANSIGenericString, Colour, Style}; use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError}; use unicode_segmentation::UnicodeSegmentation; #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub enum Destination { Stdout, Stderr, } impl Destination { pub fn isatty(&self) -> bool { match *self { Destination::Stdout => atty::is(atty::Stream::Stdout), Destination::Stderr => atty::is(atty::Stream::Stderr), } } } impl Destination { fn write(&self) -> Box<dyn Write> { match *self { Destination::Stdout => Box::new(stdout()), Destination::Stderr => Box::new(stderr()),
, Debug, PartialEq)] pub struct Theme { pub error: Style, pub warn: Style, pub info: Style, pub debug: Style, pub trace: Style, pub module: Style, } impl Theme { pub fn empty() -> Theme { Theme { error: Style::new(), warn: Style::new(), info: Style::new(), debug: Style::new(), trace: Style::new(), module: Style::new(), } } pub fn paint_log_level(&self, level: Level) -> ANSIGenericString<'static, str> { let (style, name) = match level { Level::Error => (self.error, "😡 E "), Level::Warn => (self.warn, "😥 W "), Level::Info => (self.info, "😋 I "), Level::Debug => (self.debug, "🤔 D "), Level::Trace => (self.trace, "🤓 T "), }; style.paint(name) } } impl Default for Theme { fn default() -> Theme { Theme { error: Colour::Red.bold(), warn: Colour::Yellow.bold(), info: Colour::Cyan.normal(), debug: Colour::White.normal(), trace: Colour::White.dimmed(), module: Style::new(), } } } pub fn init( destination: Destination, level: LevelFilter, theme: Theme, ) -> Result<(), SetLoggerError> { platform_init(); Logger::new(destination, level, theme).set_logger() } pub fn init_level(level: LevelFilter) -> Result<(), SetLoggerError> { platform_init(); let mut logger = Logger::default(); logger.level = level; logger.set_logger() } pub fn init_to_defaults() -> Result<(), SetLoggerError> { platform_init(); Logger::default().set_logger() } #[cfg(windows)] fn platform_init() { use ansi_term::enable_ansi_support; let _ = enable_ansi_support(); } #[cfg(not(windows))] fn platform_init() {}
} } } impl Default for Destination { fn default() -> Destination { Destination::Stderr } } pub struct Logger { destination: Destination, level: LevelFilter, max_module_width: AtomicUsize, max_target_width: AtomicUsize, theme: Theme, } impl Logger { pub fn new(destination: Destination, level: LevelFilter, theme: Theme) -> Logger { Logger { destination, level, max_module_width: AtomicUsize::new(0), max_target_width: AtomicUsize::new(0), theme, } } pub fn set_logger(self) -> Result<(), SetLoggerError> { let level = self.level; log::set_boxed_logger(Box::new(self)).map(|()| log::set_max_level(level)) } fn update_module_width(&self, width: usize) -> usize { loop { let old = self.max_module_width.load(Ordering::SeqCst); let new = max(old, width); if self .max_module_width .compare_and_swap(old, new, Ordering::SeqCst) == old { return new; } } } fn update_target_width(&self, width: usize) -> usize { loop { let old = self.max_target_width.load(Ordering::SeqCst); let new = max(old, width); if self .max_target_width .compare_and_swap(old, new, Ordering::SeqCst) == old { return new; } } } } impl Default for Logger { fn default() -> Logger { let destination = Destination::default(); let theme = if destination.isatty() { Theme::default() } else { Theme::empty() }; Logger::new(destination, LevelFilter::Info, theme) } } impl Log for Logger { fn enabled(&self, metadata: &Metadata) -> bool { self.level .to_level() .map(|level| metadata.level() <= level) .unwrap_or(false) } fn flush(&self) {} fn log(&self, record: &Record) { if !self.enabled(record.metadata()) { return; } let module = record.module_path().unwrap_or("<unknown>"); let target = record.target(); let module_length = self.update_module_width(module.graphemes(true).count()); let _ = if module == target { writeln!( self.destination.write(), "{}|{:.*}| {}", self.theme.paint_log_level(record.level()), module_length, module, record.args() ) } else { let target_length = self.update_target_width(target.graphemes(true).count()); writeln!( self.destination.write(), "{}|{:.*}|{:.*}|{}", self.theme.paint_log_level(record.level()), module_length, module, target_length, target, record.args() ) }; } } #[derive(Clone, Copy
random
[ { "content": "pub fn group(\n\n key_paths: &[PathBuf],\n\n existing_group: Option<&PathBuf>,\n\n out: Option<&PathBuf>,\n\n period: Option<Duration>,\n\n) -> Result<()> {\n\n ensure!(\n\n existing_group.is_some() || key_paths.len() >= 3,\n\n \"groups must be at least 3 nodes large\"...
Rust
src/jws/envelope.rs
andkononykhin/didcomm-rust
939e13bda8babe9c27bc197bce16c5272fc07637
use askar_crypto::sign::SignatureType; use serde::{Deserialize, Serialize}; use serde_enum_str::{Deserialize_enum_str, Serialize_enum_str}; use crate::error::{err_msg, ErrorKind, Result}; #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] pub(crate) struct JWS<'a> { pub signatures: Vec<Signature<'a>>, pub payload: &'a str, } #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] pub(crate) struct Signature<'a> { #[serde(borrow)] pub header: Header<'a>, pub protected: &'a str, pub signature: &'a str, } #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] pub(crate) struct ProtectedHeader<'a> { pub typ: &'a str, pub alg: Algorithm, } #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] pub(crate) struct Header<'a> { pub kid: &'a str, } #[derive(Deserialize_enum_str, Serialize_enum_str, Debug, Clone, Eq, PartialEq)] pub(crate) enum Algorithm { #[serde(rename = "EdDSA")] EdDSA, #[serde(rename = "ES256")] Es256, #[serde(rename = "ES256K")] Es256K, #[serde(other)] Other(String), } impl Algorithm { pub(crate) fn sig_type(&self) -> Result<SignatureType> { let sig_type = match self { Algorithm::EdDSA => SignatureType::EdDSA, Algorithm::Es256 => SignatureType::ES256, Algorithm::Es256K => SignatureType::ES256K, Algorithm::Other(_) => Err(err_msg( ErrorKind::NoCompatibleCrypto, "Unsuported signature type", ))?, }; Ok(sig_type) } } #[cfg(test)] mod tests { use super::*; #[test] fn algorithm_serialize_works() { let alg = Algorithm::EdDSA; let alg = serde_json::to_string(&alg).expect("Unable serialize"); assert_eq!(alg, "\"EdDSA\""); let alg = Algorithm::Es256; let alg = serde_json::to_string(&alg).expect("Unable serialize"); assert_eq!(alg, "\"ES256\""); let alg = Algorithm::Es256K; let alg = serde_json::to_string(&alg).expect("Unable serialize"); assert_eq!(alg, "\"ES256K\""); let alg = Algorithm::Other("Unknown".into()); let alg = serde_json::to_string(&alg).expect("Unable serialize"); assert_eq!(alg, "\"Unknown\""); let alg = Algorithm::Other("Unknown 2".into()); let alg = serde_json::to_string(&alg).expect("Unable serialize"); assert_eq!(alg, "\"Unknown 2\""); } #[test] fn algorithm_deserialize_works() { let alg: Algorithm = serde_json::from_str("\"EdDSA\"").expect("Unable deserialize"); assert_eq!(alg, Algorithm::EdDSA); let alg: Algorithm = serde_json::from_str("\"ES256\"").expect("Unable deserialize"); assert_eq!(alg, Algorithm::Es256); let alg: Algorithm = serde_json::from_str("\"ES256K\"").expect("Unable deserialize"); assert_eq!(alg, Algorithm::Es256K); let alg: Algorithm = serde_json::from_str("\"Unknown\"").expect("Unable deserialize"); assert_eq!(alg, Algorithm::Other("Unknown".into())); let alg: Algorithm = serde_json::from_str("\"Unknown 2\"").expect("Unable deserialize"); assert_eq!(alg, Algorithm::Other("Unknown 2".into())); } }
use askar_crypto::sign::SignatureType; use serde::{Deserialize, Serialize}; use serde_enum_str::{Deserialize_enum_str, Serialize_enum_str}; use crate::error::{err_msg, ErrorKind, Result}; #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] pub(crate) struct JWS<'a> { pub signatures: Vec<Signature<'a>>, pub payload: &'a str, } #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] pub(crate) struct Signature<'a> { #[serde(borrow)] pub header: Header<'a>, pub protected: &'a str, pub signature: &'a str, } #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] pub(crate) struct ProtectedHeader<'a> { pub typ: &'a str, pub alg: Algorithm, } #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)
} #[test] fn algorithm_deserialize_works() { let alg: Algorithm = serde_json::from_str("\"EdDSA\"").expect("Unable deserialize"); assert_eq!(alg, Algorithm::EdDSA); let alg: Algorithm = serde_json::from_str("\"ES256\"").expect("Unable deserialize"); assert_eq!(alg, Algorithm::Es256); let alg: Algorithm = serde_json::from_str("\"ES256K\"").expect("Unable deserialize"); assert_eq!(alg, Algorithm::Es256K); let alg: Algorithm = serde_json::from_str("\"Unknown\"").expect("Unable deserialize"); assert_eq!(alg, Algorithm::Other("Unknown".into())); let alg: Algorithm = serde_json::from_str("\"Unknown 2\"").expect("Unable deserialize"); assert_eq!(alg, Algorithm::Other("Unknown 2".into())); } }
] pub(crate) struct Header<'a> { pub kid: &'a str, } #[derive(Deserialize_enum_str, Serialize_enum_str, Debug, Clone, Eq, PartialEq)] pub(crate) enum Algorithm { #[serde(rename = "EdDSA")] EdDSA, #[serde(rename = "ES256")] Es256, #[serde(rename = "ES256K")] Es256K, #[serde(other)] Other(String), } impl Algorithm { pub(crate) fn sig_type(&self) -> Result<SignatureType> { let sig_type = match self { Algorithm::EdDSA => SignatureType::EdDSA, Algorithm::Es256 => SignatureType::ES256, Algorithm::Es256K => SignatureType::ES256K, Algorithm::Other(_) => Err(err_msg( ErrorKind::NoCompatibleCrypto, "Unsuported signature type", ))?, }; Ok(sig_type) } } #[cfg(test)] mod tests { use super::*; #[test] fn algorithm_serialize_works() { let alg = Algorithm::EdDSA; let alg = serde_json::to_string(&alg).expect("Unable serialize"); assert_eq!(alg, "\"EdDSA\""); let alg = Algorithm::Es256; let alg = serde_json::to_string(&alg).expect("Unable serialize"); assert_eq!(alg, "\"ES256\""); let alg = Algorithm::Es256K; let alg = serde_json::to_string(&alg).expect("Unable serialize"); assert_eq!(alg, "\"ES256K\""); let alg = Algorithm::Other("Unknown".into()); let alg = serde_json::to_string(&alg).expect("Unable serialize"); assert_eq!(alg, "\"Unknown\""); let alg = Algorithm::Other("Unknown 2".into()); let alg = serde_json::to_string(&alg).expect("Unable serialize"); assert_eq!(alg, "\"Unknown 2\"");
random
[ { "content": "pub trait ResultContext<T> {\n\n fn context<D>(self, msg: D) -> Result<T>\n\n where\n\n D: fmt::Display + fmt::Debug + Send + Sync + 'static;\n\n}\n\n\n\nimpl<T> ResultContext<T> for Result<T> {\n\n fn context<D>(self, msg: D) -> Result<T>\n\n where\n\n D: fmt::Display + ...
Rust
src/backend/wgpu_impl/shape_vertex_layout.rs
eaglekindoms/LemoGUI
a1499502c2f87cd8919b4de0ac26363b1755bf4a
use wgpu::*; use crate::backend::wgpu_impl::*; use crate::device::GPUContext; use crate::graphic::base::*; use crate::graphic::style::{Bordering, Rounding, Style}; #[repr(C)] #[derive(Copy, Default, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct CircleVertex { pub position: [f32; 2], pub color: [f32; 4], pub radius: f32, pub edge: u32, } impl CircleVertex { pub fn new(point: &Circle, edge: u32, color: RGBA) -> Self { log::info!("create the PolygonVertex obj"); Self { position: [point.position.x, point.position.y], color: color.to_vec(), radius: point.radius, edge, } } } const CIRCLE_ATTRS: [VertexAttribute; 4] = wgpu::vertex_attr_array![ 0 => Float32x2, 1 => Float32x4, 2 => Float32, 3 => Uint32]; impl VertexLayout for CircleVertex { fn set_vertex_desc<'a>() -> VertexBufferLayout<'a> { wgpu::VertexBufferLayout { array_stride: std::mem::size_of::<CircleVertex>() as wgpu::BufferAddress, step_mode: wgpu::VertexStepMode::Instance, attributes: &CIRCLE_ATTRS, } } fn get_shader(device: &Device) -> ShaderModule { device.create_shader_module(&wgpu::ShaderModuleDescriptor { label: Some("circle shader"), source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed( include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/shader_c/circle.wgsl")), )), }) } } #[derive(Debug, Default, Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] #[repr(C)] pub struct RectVertex { pub size: [f32; 2], pub position: [f32; 2], pub border_color: [f32; 4], pub rect_color: [f32; 4], pub is_round_or_border: [u32; 2], } const RECT_ATTRS: [VertexAttribute; 5] = wgpu::vertex_attr_array![ 0 => Float32x2, 1 => Float32x2, 2 => Float32x4, 3 => Float32x4, 4 => Uint32x2]; impl VertexLayout for RectVertex { fn set_vertex_desc<'a>() -> VertexBufferLayout<'a> { wgpu::VertexBufferLayout { array_stride: std::mem::size_of::<RectVertex>() as wgpu::BufferAddress, step_mode: wgpu::VertexStepMode::Instance, attributes: &RECT_ATTRS, } } fn get_shader(device: &Device) -> ShaderModule { device.create_shader_module(&wgpu::ShaderModuleDescriptor { label: Some("round_rect shader"), source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed( include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/shader_c/round_rect.wgsl")), )), }) } } impl RectVertex { pub fn new(rect: &Rectangle, style: Style) -> RectVertex { let mut border_color = [0.0, 0.0, 0.0, 0.0]; let rect_color = style.get_display_color().to_vec(); let is_round; let is_border; match style.get_round() { Rounding::Round => { is_round = 1 } Rounding::NoRound => { is_round = 0 } } match style.get_border() { Bordering::Border(color) => { is_border = 1; border_color = color.to_vec() } Bordering::NoBorder => { is_border = 0 } } RectVertex { size: [rect.width as f32, rect.height as f32], position: [rect.position.x, rect.position.y], border_color, rect_color, is_round_or_border: [is_round, is_border], } } } #[repr(C)] #[derive(Copy, Default, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct PointVertex { pub position: [f32; 2], pub color: [f32; 4], } impl PointVertex { pub fn new(x: f32, y: f32, color: RGBA) -> Self { log::info!("create the PointVertex obj"); Self { position: [x, y], color: color.to_vec(), } } } const POINT_ATTRS: [VertexAttribute; 2] = wgpu::vertex_attr_array![ 0 => Float32x2, 1 => Float32x4 ]; impl VertexLayout for PointVertex { fn set_vertex_desc<'a>() -> VertexBufferLayout<'a> { wgpu::VertexBufferLayout { array_stride: std::mem::size_of::<PointVertex>() as wgpu::BufferAddress, step_mode: wgpu::VertexStepMode::Vertex, attributes: &POINT_ATTRS, } } fn get_shader(device: &Device) -> ShaderModule { device.create_shader_module(&wgpu::ShaderModuleDescriptor { label: Some("triangle shader"), source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed( include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/shader_c/triangle.wgsl")), )), }) } } impl PointVertex { pub fn from_shape_to_vector(gpu_context: &GPUContext, points: &Vec<Point<f32>>, color: RGBA) -> VertexBuffer { let vertex_nums = (points.len() - 3) * 2 + points.len(); let mut vect = Vec::with_capacity(points.len()); let mut indices = Vec::with_capacity(vertex_nums); for i in 0..points.len() { vect.push(PointVertex::new(points[i].x, points[i].y, color)); } let mut i = 1u16; while i < points.len() as u16 - 1 { indices.push(0); indices.push(i); i = i + 1; indices.push(i); } let point_buffer = VertexBuffer::create_vertex_buf::<PointVertex> (&gpu_context.device, vect, indices.as_slice()); point_buffer } }
use wgpu::*; use crate::backend::wgpu_impl::*; use crate::device::GPUContext; use crate::graphic::base::*; use crate::graphic::style::{Bordering, Rounding, Style}; #[repr(C)] #[derive(Copy, Default, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct CircleVertex { pub position: [f32; 2], pub color: [f32; 4], pub radius: f32, pub edge: u32, } impl CircleVertex { pub fn new(point: &Circle, edge: u32, color: RGBA) -> Self { log::info!("create the PolygonVertex obj"); Self { position: [point.position.x, point.position.y], color: color.to_vec(), radius: point.radius, edge, } } } const CIRCLE_ATTRS: [VertexAttribute; 4] = wgpu::vertex_attr_array![ 0 => Float32x2, 1 => Float32x4, 2 => Float32, 3 => Uint32]; impl VertexLayout for CircleVertex { fn set_vertex_desc<'a>() -> VertexBufferLayout<'a> { wgpu::VertexBufferLayout { array_stride: std::mem::size_of::<CircleVertex>() as wgpu::BufferAddress, step_mode: wgpu::VertexStepMode::Instance, attributes: &CIRCLE_ATTRS, } } fn get_shader(device: &Device) -> ShaderModule { device.create_shader_module(&wgpu::ShaderModuleDescriptor { label: Some("circle shader"), source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed( include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/shader_c/circle.wgsl")), )), }) } } #[derive(Debug, Default, Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] #[repr(C)] pub struct RectV
::ShaderModuleDescriptor { label: Some("round_rect shader"), source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed( include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/shader_c/round_rect.wgsl")), )), }) } } impl RectVertex { pub fn new(rect: &Rectangle, style: Style) -> RectVertex { let mut border_color = [0.0, 0.0, 0.0, 0.0]; let rect_color = style.get_display_color().to_vec(); let is_round; let is_border; match style.get_round() { Rounding::Round => { is_round = 1 } Rounding::NoRound => { is_round = 0 } } match style.get_border() { Bordering::Border(color) => { is_border = 1; border_color = color.to_vec() } Bordering::NoBorder => { is_border = 0 } } RectVertex { size: [rect.width as f32, rect.height as f32], position: [rect.position.x, rect.position.y], border_color, rect_color, is_round_or_border: [is_round, is_border], } } } #[repr(C)] #[derive(Copy, Default, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct PointVertex { pub position: [f32; 2], pub color: [f32; 4], } impl PointVertex { pub fn new(x: f32, y: f32, color: RGBA) -> Self { log::info!("create the PointVertex obj"); Self { position: [x, y], color: color.to_vec(), } } } const POINT_ATTRS: [VertexAttribute; 2] = wgpu::vertex_attr_array![ 0 => Float32x2, 1 => Float32x4 ]; impl VertexLayout for PointVertex { fn set_vertex_desc<'a>() -> VertexBufferLayout<'a> { wgpu::VertexBufferLayout { array_stride: std::mem::size_of::<PointVertex>() as wgpu::BufferAddress, step_mode: wgpu::VertexStepMode::Vertex, attributes: &POINT_ATTRS, } } fn get_shader(device: &Device) -> ShaderModule { device.create_shader_module(&wgpu::ShaderModuleDescriptor { label: Some("triangle shader"), source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed( include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/shader_c/triangle.wgsl")), )), }) } } impl PointVertex { pub fn from_shape_to_vector(gpu_context: &GPUContext, points: &Vec<Point<f32>>, color: RGBA) -> VertexBuffer { let vertex_nums = (points.len() - 3) * 2 + points.len(); let mut vect = Vec::with_capacity(points.len()); let mut indices = Vec::with_capacity(vertex_nums); for i in 0..points.len() { vect.push(PointVertex::new(points[i].x, points[i].y, color)); } let mut i = 1u16; while i < points.len() as u16 - 1 { indices.push(0); indices.push(i); i = i + 1; indices.push(i); } let point_buffer = VertexBuffer::create_vertex_buf::<PointVertex> (&gpu_context.device, vect, indices.as_slice()); point_buffer } }
ertex { pub size: [f32; 2], pub position: [f32; 2], pub border_color: [f32; 4], pub rect_color: [f32; 4], pub is_round_or_border: [u32; 2], } const RECT_ATTRS: [VertexAttribute; 5] = wgpu::vertex_attr_array![ 0 => Float32x2, 1 => Float32x2, 2 => Float32x4, 3 => Float32x4, 4 => Uint32x2]; impl VertexLayout for RectVertex { fn set_vertex_desc<'a>() -> VertexBufferLayout<'a> { wgpu::VertexBufferLayout { array_stride: std::mem::size_of::<RectVertex>() as wgpu::BufferAddress, step_mode: wgpu::VertexStepMode::Instance, attributes: &RECT_ATTRS, } } fn get_shader(device: &Device) -> ShaderModule { device.create_shader_module(&wgpu
random
[ { "content": "/// 描述纹理顶点数据布局,用于着色器识别数据\n\npub fn bind_group(device: &wgpu::Device,\n\n bind_group_layout: &wgpu::BindGroupLayout,\n\n target: &wgpu::TextureView,\n\n sampler: &wgpu::Sampler) -> wgpu::BindGroup\n\n{\n\n device.create_bind_group(\n\n &w...
Rust
src/rustc/middle/trans/impl.rs
mernen/rust
bb5c07922f20559af1e40d63a15b1be0402e5fe4
import libc::c_uint; import base::*; import common::*; import type_of::*; import build::*; import driver::session::session; import syntax::{ast, ast_map}; import ast_map::{path, path_mod, path_name, node_id_to_str}; import driver::session::expect; import syntax::ast_util::local_def; import metadata::csearch; import back::{link, abi}; import lib::llvm::llvm; import lib::llvm::{ValueRef, TypeRef}; import lib::llvm::llvm::LLVMGetParam; import std::map::hashmap; import util::ppaux::{ty_to_str, tys_to_str}; import syntax::print::pprust::expr_to_str; /** The main "translation" pass for methods. Generates code for non-monomorphized methods only. Other methods will be generated once they are invoked with specific type parameters, see `trans::base::lval_static_fn()` or `trans::base::monomorphic_fn()`. */ fn trans_impl(ccx: @crate_ctxt, path: path, name: ast::ident, methods: ~[@ast::method], tps: ~[ast::ty_param]) { let _icx = ccx.insn_ctxt("impl::trans_impl"); if tps.len() > 0u { return; } let sub_path = vec::append_one(path, path_name(name)); for vec::each(methods) |method| { if method.tps.len() == 0u { let llfn = get_item_val(ccx, method.id); let path = vec::append_one(sub_path, path_name(method.ident)); trans_method(ccx, path, method, none, llfn); } } } /** Translates a (possibly monomorphized) method body. # Parameters - `path`: the path to the method - `method`: the AST node for the method - `param_substs`: if this is a generic method, the current values for type parameters and so forth, else none - `llfn`: the LLVM ValueRef for the method */ fn trans_method(ccx: @crate_ctxt, path: path, method: &ast::method, param_substs: option<param_substs>, llfn: ValueRef) { let self_arg = match method.self_ty.node { ast::sty_static => { no_self } _ => { let self_ty = ty::node_id_to_type(ccx.tcx, method.self_id); let self_ty = match param_substs { none => self_ty, some({tys: ref tys, _}) => ty::subst_tps(ccx.tcx, *tys, self_ty) }; match method.self_ty.node { ast::sty_value => { impl_owned_self(self_ty) } _ => { impl_self(self_ty) } } } }; trans_fn(ccx, path, method.decl, method.body, llfn, self_arg, param_substs, method.id); } fn trans_self_arg(bcx: block, base: @ast::expr, mentry: typeck::method_map_entry) -> result { let _icx = bcx.insn_ctxt("impl::trans_self_arg"); let basety = expr_ty(bcx, base); let mode = ast::expl(mentry.self_mode); let mut temp_cleanups = ~[]; let result = trans_arg_expr(bcx, {mode: mode, ty: basety}, T_ptr(type_of::type_of(bcx.ccx(), basety)), base, temp_cleanups, none, mentry.derefs); return result; } fn trans_method_callee(bcx: block, callee_id: ast::node_id, self: @ast::expr, mentry: typeck::method_map_entry) -> lval_maybe_callee { let _icx = bcx.insn_ctxt("impl::trans_method_callee"); match mentry.origin { typeck::method_static(did) => { let {bcx, val} = trans_self_arg(bcx, self, mentry); {env: self_env(val, node_id_type(bcx, self.id), none, mentry.self_mode) with lval_static_fn(bcx, did, callee_id)} } typeck::method_param({trait_id:trait_id, method_num:off, param_num:p, bound_num:b}) => { match bcx.fcx.param_substs { some(substs) => { let vtbl = find_vtable_in_fn_ctxt(substs, p, b); trans_monomorphized_callee(bcx, callee_id, self, mentry, trait_id, off, vtbl) } none => fail ~"trans_method_callee: missing param_substs" } } typeck::method_trait(_, off) => { let {bcx, val} = trans_temp_expr(bcx, self); let fty = node_id_type(bcx, callee_id); let self_ty = node_id_type(bcx, self.id); let {bcx, val, _} = autoderef(bcx, self.id, val, self_ty, uint::max_value); trans_trait_callee(bcx, val, fty, off) } } } fn trans_static_method_callee(bcx: block, method_id: ast::def_id, callee_id: ast::node_id) -> lval_maybe_callee { let _icx = bcx.insn_ctxt("impl::trans_static_method_callee"); let ccx = bcx.ccx(); let mname = if method_id.crate == ast::local_crate { match bcx.tcx().items.get(method_id.node) { ast_map::node_trait_method(trait_method, _, _) => { ast_util::trait_method_to_ty_method(*trait_method).ident } _ => fail ~"callee is not a trait method" } } else { let path = csearch::get_item_path(bcx.tcx(), method_id); match path[path.len()-1] { path_name(s) => { s } path_mod(_) => { fail ~"path doesn't have a name?" } } }; debug!("trans_static_method_callee: method_id=%?, callee_id=%?, \ name=%s", method_id, callee_id, ccx.sess.str_of(mname)); let vtbls = resolve_vtables_in_fn_ctxt( bcx.fcx, ccx.maps.vtable_map.get(callee_id)); match vtbls[0] { typeck::vtable_static(impl_did, impl_substs, sub_origins) => { let mth_id = method_with_name(bcx.ccx(), impl_did, mname); let n_m_tps = method_ty_param_count(ccx, mth_id, impl_did); let node_substs = node_id_type_params(bcx, callee_id); let ty_substs = vec::append(impl_substs, vec::tailn(node_substs, node_substs.len() - n_m_tps)); let lval = lval_static_fn_inner(bcx, mth_id, callee_id, ty_substs, some(sub_origins)); {env: null_env, val: PointerCast(bcx, lval.val, T_ptr(type_of_fn_from_ty( ccx, node_id_type(bcx, callee_id)))) with lval} } _ => { fail ~"vtable_param left in monomorphized function's vtable substs"; } } } fn method_from_methods(ms: ~[@ast::method], name: ast::ident) -> ast::def_id { local_def(option::get(vec::find(ms, |m| m.ident == name)).id) } fn method_with_name(ccx: @crate_ctxt, impl_id: ast::def_id, name: ast::ident) -> ast::def_id { if impl_id.crate == ast::local_crate { match ccx.tcx.items.get(impl_id.node) { ast_map::node_item(@{node: ast::item_impl(_, _, _, ms), _}, _) => { method_from_methods(ms, name) } ast_map::node_item(@{node: ast::item_class(struct_def, _), _}, _) => { method_from_methods(struct_def.methods, name) } _ => fail ~"method_with_name" } } else { csearch::get_impl_method(ccx.sess.cstore, impl_id, name) } } fn method_ty_param_count(ccx: @crate_ctxt, m_id: ast::def_id, i_id: ast::def_id) -> uint { if m_id.crate == ast::local_crate { match ccx.tcx.items.get(m_id.node) { ast_map::node_method(m, _, _) => vec::len(m.tps), _ => fail ~"method_ty_param_count" } } else { csearch::get_type_param_count(ccx.sess.cstore, m_id) - csearch::get_type_param_count(ccx.sess.cstore, i_id) } } fn trans_monomorphized_callee(bcx: block, callee_id: ast::node_id, base: @ast::expr, mentry: typeck::method_map_entry, trait_id: ast::def_id, n_method: uint, vtbl: typeck::vtable_origin) -> lval_maybe_callee { let _icx = bcx.insn_ctxt("impl::trans_monomorphized_callee"); match vtbl { typeck::vtable_static(impl_did, impl_substs, sub_origins) => { let ccx = bcx.ccx(); let mname = ty::trait_methods(ccx.tcx, trait_id)[n_method].ident; let mth_id = method_with_name(bcx.ccx(), impl_did, mname); let n_m_tps = method_ty_param_count(ccx, mth_id, impl_did); let node_substs = node_id_type_params(bcx, callee_id); let ty_substs = vec::append(impl_substs, vec::tailn(node_substs, node_substs.len() - n_m_tps)); let {bcx, val} = trans_self_arg(bcx, base, mentry); let lval = lval_static_fn_inner(bcx, mth_id, callee_id, ty_substs, some(sub_origins)); {env: self_env(val, node_id_type(bcx, base.id), none, mentry.self_mode), val: PointerCast(bcx, lval.val, T_ptr(type_of_fn_from_ty( ccx, node_id_type(bcx, callee_id)))) with lval} } typeck::vtable_trait(trait_id, tps) => { let {bcx, val} = trans_temp_expr(bcx, base); let fty = node_id_type(bcx, callee_id); trans_trait_callee(bcx, val, fty, n_method) } typeck::vtable_param(n_param, n_bound) => { fail ~"vtable_param left in monomorphized function's vtable substs"; } } } fn trans_trait_callee(bcx: block, val: ValueRef, callee_ty: ty::t, n_method: uint) -> lval_maybe_callee { let _icx = bcx.insn_ctxt("impl::trans_trait_callee"); let ccx = bcx.ccx(); let vtable = Load(bcx, PointerCast(bcx, GEPi(bcx, val, ~[0u, 0u]), T_ptr(T_ptr(T_vtable())))); let llbox = Load(bcx, GEPi(bcx, val, ~[0u, 1u])); let self = GEPi(bcx, llbox, ~[0u, abi::box_field_body]); let env = self_env(self, ty::mk_opaque_box(bcx.tcx()), some(llbox), ast::by_ref); let llfty = type_of::type_of_fn_from_ty(ccx, callee_ty); let vtable = PointerCast(bcx, vtable, T_ptr(T_array(T_ptr(llfty), n_method + 1u))); let mptr = Load(bcx, GEPi(bcx, vtable, ~[0u, n_method])); {bcx: bcx, val: mptr, kind: lv_owned, env: env} } fn find_vtable_in_fn_ctxt(ps: param_substs, n_param: uint, n_bound: uint) -> typeck::vtable_origin { let mut vtable_off = n_bound, i = 0u; for vec::each(*ps.bounds) |bounds| { if i >= n_param { break; } for vec::each(*bounds) |bound| { match bound { ty::bound_trait(_) => vtable_off += 1u, _ => () } } i += 1u; } option::get(ps.vtables)[vtable_off] } fn resolve_vtables_in_fn_ctxt(fcx: fn_ctxt, vts: typeck::vtable_res) -> typeck::vtable_res { @vec::map(*vts, |d| resolve_vtable_in_fn_ctxt(fcx, d)) } fn resolve_vtable_in_fn_ctxt(fcx: fn_ctxt, vt: typeck::vtable_origin) -> typeck::vtable_origin { match vt { typeck::vtable_static(trait_id, tys, sub) => { let tys = match fcx.param_substs { some(substs) => { vec::map(tys, |t| ty::subst_tps(fcx.ccx.tcx, substs.tys, t)) } _ => tys }; typeck::vtable_static(trait_id, tys, resolve_vtables_in_fn_ctxt(fcx, sub)) } typeck::vtable_param(n_param, n_bound) => { match fcx.param_substs { some(substs) => { find_vtable_in_fn_ctxt(substs, n_param, n_bound) } _ => fail ~"resolve_vtable_in_fn_ctxt: no substs" } } _ => vt } } fn vtable_id(ccx: @crate_ctxt, origin: typeck::vtable_origin) -> mono_id { match origin { typeck::vtable_static(impl_id, substs, sub_vtables) => { make_mono_id(ccx, impl_id, substs, if (*sub_vtables).len() == 0u { none } else { some(sub_vtables) }, none) } typeck::vtable_trait(trait_id, substs) => { @{def: trait_id, params: vec::map(substs, |t| mono_precise(t, none))} } _ => fail ~"vtable_id" } } fn get_vtable(ccx: @crate_ctxt, origin: typeck::vtable_origin) -> ValueRef { let hash_id = vtable_id(ccx, origin); match ccx.vtables.find(hash_id) { some(val) => val, none => match origin { typeck::vtable_static(id, substs, sub_vtables) => { make_impl_vtable(ccx, id, substs, sub_vtables) } _ => fail ~"get_vtable: expected a static origin" } } } fn make_vtable(ccx: @crate_ctxt, ptrs: ~[ValueRef]) -> ValueRef { let _icx = ccx.insn_ctxt("impl::make_vtable"); let tbl = C_struct(ptrs); let vt_gvar = str::as_c_str(ccx.sess.str_of(ccx.names(~"vtable")), |buf| { llvm::LLVMAddGlobal(ccx.llmod, val_ty(tbl), buf) }); llvm::LLVMSetInitializer(vt_gvar, tbl); llvm::LLVMSetGlobalConstant(vt_gvar, lib::llvm::True); lib::llvm::SetLinkage(vt_gvar, lib::llvm::InternalLinkage); vt_gvar } fn make_impl_vtable(ccx: @crate_ctxt, impl_id: ast::def_id, substs: ~[ty::t], vtables: typeck::vtable_res) -> ValueRef { let _icx = ccx.insn_ctxt("impl::make_impl_vtable"); let tcx = ccx.tcx; let trt_id = expect(ccx.sess, ty::ty_to_def_id(ty::impl_traits(tcx, impl_id)[0]), || ~"make_impl_vtable: non-trait-type implemented"); let has_tps = (*ty::lookup_item_type(ccx.tcx, impl_id).bounds).len() > 0u; make_vtable(ccx, vec::map(*ty::trait_methods(tcx, trt_id), |im| { let fty = ty::subst_tps(tcx, substs, ty::mk_fn(tcx, im.fty)); if (*im.tps).len() > 0u || ty::type_has_self(fty) { C_null(T_ptr(T_nil())) } else { let mut m_id = method_with_name(ccx, impl_id, im.ident); if has_tps { if m_id.crate != ast::local_crate { m_id = maybe_instantiate_inline(ccx, m_id); } monomorphic_fn(ccx, m_id, substs, some(vtables), none).val } else if m_id.crate == ast::local_crate { get_item_val(ccx, m_id.node) } else { trans_external_path(ccx, m_id, fty) } } })) } fn trans_cast(bcx: block, val: @ast::expr, id: ast::node_id, dest: dest) -> block { let _icx = bcx.insn_ctxt("impl::trans_cast"); if dest == ignore { return trans_expr(bcx, val, ignore); } let ccx = bcx.ccx(); let v_ty = expr_ty(bcx, val); let {bcx: bcx, box: llbox, body: body} = malloc_boxed(bcx, v_ty); add_clean_free(bcx, llbox, heap_shared); let bcx = trans_expr_save_in(bcx, val, body); revoke_clean(bcx, llbox); let result = get_dest_addr(dest); Store(bcx, llbox, PointerCast(bcx, GEPi(bcx, result, ~[0u, 1u]), T_ptr(val_ty(llbox)))); let orig = ccx.maps.vtable_map.get(id)[0]; let orig = resolve_vtable_in_fn_ctxt(bcx.fcx, orig); let vtable = get_vtable(bcx.ccx(), orig); Store(bcx, vtable, PointerCast(bcx, GEPi(bcx, result, ~[0u, 0u]), T_ptr(val_ty(vtable)))); bcx }
import libc::c_uint; import base::*; import common::*; import type_of::*; import build::*; import driver::session::session; import syntax::{ast, ast_map}; import ast_map::{path, path_mod, path_name, node_id_to_str}; import driver::session::expect; import syntax::ast_util::local_def; import metadata::csearch; import back::{link, abi}; import lib::llvm::llvm; import lib::llvm::{ValueRef, TypeRef}; import lib::llvm::llvm::LLVMGetParam; import std::map::hashmap; import util::ppaux::{ty_to_str, tys_to_str}; import syntax::print::pprust::expr_to_str; /** The main "translation" pass for methods. Generates code for non-monomorphized methods only. Other methods will be generated once they are invoked with specific type parameters, see `trans::base::lval_static_fn()` or `trans::base::monomorphic_fn()`. */ fn trans_impl(ccx: @crate_ctxt, path: path, name: ast::ident, methods: ~[@ast::method], tps: ~[ast::ty_param]) { let _icx = ccx.insn_ctxt("impl::trans_impl"); if tps.len() > 0u { return; } let sub_path = vec::append_one(path, path_name(name)); for vec::each(methods) |method| { if method.tps.len() == 0u { let llfn = get_item_val(ccx, method.id); let path = vec::append_one(sub_path, path_name(method.ident)); trans_method(ccx, path, method, none, llfn); } } } /** Translates a (possibly monomorphized) method body. # Parameters - `path`: the path to the method - `method`: the AST node for the method - `param_substs`: if this is a generic method, the current values for type parameters and so forth, else none - `llfn`: the LLVM ValueRef for the method */
fn trans_self_arg(bcx: block, base: @ast::expr, mentry: typeck::method_map_entry) -> result { let _icx = bcx.insn_ctxt("impl::trans_self_arg"); let basety = expr_ty(bcx, base); let mode = ast::expl(mentry.self_mode); let mut temp_cleanups = ~[]; let result = trans_arg_expr(bcx, {mode: mode, ty: basety}, T_ptr(type_of::type_of(bcx.ccx(), basety)), base, temp_cleanups, none, mentry.derefs); return result; } fn trans_method_callee(bcx: block, callee_id: ast::node_id, self: @ast::expr, mentry: typeck::method_map_entry) -> lval_maybe_callee { let _icx = bcx.insn_ctxt("impl::trans_method_callee"); match mentry.origin { typeck::method_static(did) => { let {bcx, val} = trans_self_arg(bcx, self, mentry); {env: self_env(val, node_id_type(bcx, self.id), none, mentry.self_mode) with lval_static_fn(bcx, did, callee_id)} } typeck::method_param({trait_id:trait_id, method_num:off, param_num:p, bound_num:b}) => { match bcx.fcx.param_substs { some(substs) => { let vtbl = find_vtable_in_fn_ctxt(substs, p, b); trans_monomorphized_callee(bcx, callee_id, self, mentry, trait_id, off, vtbl) } none => fail ~"trans_method_callee: missing param_substs" } } typeck::method_trait(_, off) => { let {bcx, val} = trans_temp_expr(bcx, self); let fty = node_id_type(bcx, callee_id); let self_ty = node_id_type(bcx, self.id); let {bcx, val, _} = autoderef(bcx, self.id, val, self_ty, uint::max_value); trans_trait_callee(bcx, val, fty, off) } } } fn trans_static_method_callee(bcx: block, method_id: ast::def_id, callee_id: ast::node_id) -> lval_maybe_callee { let _icx = bcx.insn_ctxt("impl::trans_static_method_callee"); let ccx = bcx.ccx(); let mname = if method_id.crate == ast::local_crate { match bcx.tcx().items.get(method_id.node) { ast_map::node_trait_method(trait_method, _, _) => { ast_util::trait_method_to_ty_method(*trait_method).ident } _ => fail ~"callee is not a trait method" } } else { let path = csearch::get_item_path(bcx.tcx(), method_id); match path[path.len()-1] { path_name(s) => { s } path_mod(_) => { fail ~"path doesn't have a name?" } } }; debug!("trans_static_method_callee: method_id=%?, callee_id=%?, \ name=%s", method_id, callee_id, ccx.sess.str_of(mname)); let vtbls = resolve_vtables_in_fn_ctxt( bcx.fcx, ccx.maps.vtable_map.get(callee_id)); match vtbls[0] { typeck::vtable_static(impl_did, impl_substs, sub_origins) => { let mth_id = method_with_name(bcx.ccx(), impl_did, mname); let n_m_tps = method_ty_param_count(ccx, mth_id, impl_did); let node_substs = node_id_type_params(bcx, callee_id); let ty_substs = vec::append(impl_substs, vec::tailn(node_substs, node_substs.len() - n_m_tps)); let lval = lval_static_fn_inner(bcx, mth_id, callee_id, ty_substs, some(sub_origins)); {env: null_env, val: PointerCast(bcx, lval.val, T_ptr(type_of_fn_from_ty( ccx, node_id_type(bcx, callee_id)))) with lval} } _ => { fail ~"vtable_param left in monomorphized function's vtable substs"; } } } fn method_from_methods(ms: ~[@ast::method], name: ast::ident) -> ast::def_id { local_def(option::get(vec::find(ms, |m| m.ident == name)).id) } fn method_with_name(ccx: @crate_ctxt, impl_id: ast::def_id, name: ast::ident) -> ast::def_id { if impl_id.crate == ast::local_crate { match ccx.tcx.items.get(impl_id.node) { ast_map::node_item(@{node: ast::item_impl(_, _, _, ms), _}, _) => { method_from_methods(ms, name) } ast_map::node_item(@{node: ast::item_class(struct_def, _), _}, _) => { method_from_methods(struct_def.methods, name) } _ => fail ~"method_with_name" } } else { csearch::get_impl_method(ccx.sess.cstore, impl_id, name) } } fn method_ty_param_count(ccx: @crate_ctxt, m_id: ast::def_id, i_id: ast::def_id) -> uint { if m_id.crate == ast::local_crate { match ccx.tcx.items.get(m_id.node) { ast_map::node_method(m, _, _) => vec::len(m.tps), _ => fail ~"method_ty_param_count" } } else { csearch::get_type_param_count(ccx.sess.cstore, m_id) - csearch::get_type_param_count(ccx.sess.cstore, i_id) } } fn trans_monomorphized_callee(bcx: block, callee_id: ast::node_id, base: @ast::expr, mentry: typeck::method_map_entry, trait_id: ast::def_id, n_method: uint, vtbl: typeck::vtable_origin) -> lval_maybe_callee { let _icx = bcx.insn_ctxt("impl::trans_monomorphized_callee"); match vtbl { typeck::vtable_static(impl_did, impl_substs, sub_origins) => { let ccx = bcx.ccx(); let mname = ty::trait_methods(ccx.tcx, trait_id)[n_method].ident; let mth_id = method_with_name(bcx.ccx(), impl_did, mname); let n_m_tps = method_ty_param_count(ccx, mth_id, impl_did); let node_substs = node_id_type_params(bcx, callee_id); let ty_substs = vec::append(impl_substs, vec::tailn(node_substs, node_substs.len() - n_m_tps)); let {bcx, val} = trans_self_arg(bcx, base, mentry); let lval = lval_static_fn_inner(bcx, mth_id, callee_id, ty_substs, some(sub_origins)); {env: self_env(val, node_id_type(bcx, base.id), none, mentry.self_mode), val: PointerCast(bcx, lval.val, T_ptr(type_of_fn_from_ty( ccx, node_id_type(bcx, callee_id)))) with lval} } typeck::vtable_trait(trait_id, tps) => { let {bcx, val} = trans_temp_expr(bcx, base); let fty = node_id_type(bcx, callee_id); trans_trait_callee(bcx, val, fty, n_method) } typeck::vtable_param(n_param, n_bound) => { fail ~"vtable_param left in monomorphized function's vtable substs"; } } } fn trans_trait_callee(bcx: block, val: ValueRef, callee_ty: ty::t, n_method: uint) -> lval_maybe_callee { let _icx = bcx.insn_ctxt("impl::trans_trait_callee"); let ccx = bcx.ccx(); let vtable = Load(bcx, PointerCast(bcx, GEPi(bcx, val, ~[0u, 0u]), T_ptr(T_ptr(T_vtable())))); let llbox = Load(bcx, GEPi(bcx, val, ~[0u, 1u])); let self = GEPi(bcx, llbox, ~[0u, abi::box_field_body]); let env = self_env(self, ty::mk_opaque_box(bcx.tcx()), some(llbox), ast::by_ref); let llfty = type_of::type_of_fn_from_ty(ccx, callee_ty); let vtable = PointerCast(bcx, vtable, T_ptr(T_array(T_ptr(llfty), n_method + 1u))); let mptr = Load(bcx, GEPi(bcx, vtable, ~[0u, n_method])); {bcx: bcx, val: mptr, kind: lv_owned, env: env} } fn find_vtable_in_fn_ctxt(ps: param_substs, n_param: uint, n_bound: uint) -> typeck::vtable_origin { let mut vtable_off = n_bound, i = 0u; for vec::each(*ps.bounds) |bounds| { if i >= n_param { break; } for vec::each(*bounds) |bound| { match bound { ty::bound_trait(_) => vtable_off += 1u, _ => () } } i += 1u; } option::get(ps.vtables)[vtable_off] } fn resolve_vtables_in_fn_ctxt(fcx: fn_ctxt, vts: typeck::vtable_res) -> typeck::vtable_res { @vec::map(*vts, |d| resolve_vtable_in_fn_ctxt(fcx, d)) } fn resolve_vtable_in_fn_ctxt(fcx: fn_ctxt, vt: typeck::vtable_origin) -> typeck::vtable_origin { match vt { typeck::vtable_static(trait_id, tys, sub) => { let tys = match fcx.param_substs { some(substs) => { vec::map(tys, |t| ty::subst_tps(fcx.ccx.tcx, substs.tys, t)) } _ => tys }; typeck::vtable_static(trait_id, tys, resolve_vtables_in_fn_ctxt(fcx, sub)) } typeck::vtable_param(n_param, n_bound) => { match fcx.param_substs { some(substs) => { find_vtable_in_fn_ctxt(substs, n_param, n_bound) } _ => fail ~"resolve_vtable_in_fn_ctxt: no substs" } } _ => vt } } fn vtable_id(ccx: @crate_ctxt, origin: typeck::vtable_origin) -> mono_id { match origin { typeck::vtable_static(impl_id, substs, sub_vtables) => { make_mono_id(ccx, impl_id, substs, if (*sub_vtables).len() == 0u { none } else { some(sub_vtables) }, none) } typeck::vtable_trait(trait_id, substs) => { @{def: trait_id, params: vec::map(substs, |t| mono_precise(t, none))} } _ => fail ~"vtable_id" } } fn get_vtable(ccx: @crate_ctxt, origin: typeck::vtable_origin) -> ValueRef { let hash_id = vtable_id(ccx, origin); match ccx.vtables.find(hash_id) { some(val) => val, none => match origin { typeck::vtable_static(id, substs, sub_vtables) => { make_impl_vtable(ccx, id, substs, sub_vtables) } _ => fail ~"get_vtable: expected a static origin" } } } fn make_vtable(ccx: @crate_ctxt, ptrs: ~[ValueRef]) -> ValueRef { let _icx = ccx.insn_ctxt("impl::make_vtable"); let tbl = C_struct(ptrs); let vt_gvar = str::as_c_str(ccx.sess.str_of(ccx.names(~"vtable")), |buf| { llvm::LLVMAddGlobal(ccx.llmod, val_ty(tbl), buf) }); llvm::LLVMSetInitializer(vt_gvar, tbl); llvm::LLVMSetGlobalConstant(vt_gvar, lib::llvm::True); lib::llvm::SetLinkage(vt_gvar, lib::llvm::InternalLinkage); vt_gvar } fn make_impl_vtable(ccx: @crate_ctxt, impl_id: ast::def_id, substs: ~[ty::t], vtables: typeck::vtable_res) -> ValueRef { let _icx = ccx.insn_ctxt("impl::make_impl_vtable"); let tcx = ccx.tcx; let trt_id = expect(ccx.sess, ty::ty_to_def_id(ty::impl_traits(tcx, impl_id)[0]), || ~"make_impl_vtable: non-trait-type implemented"); let has_tps = (*ty::lookup_item_type(ccx.tcx, impl_id).bounds).len() > 0u; make_vtable(ccx, vec::map(*ty::trait_methods(tcx, trt_id), |im| { let fty = ty::subst_tps(tcx, substs, ty::mk_fn(tcx, im.fty)); if (*im.tps).len() > 0u || ty::type_has_self(fty) { C_null(T_ptr(T_nil())) } else { let mut m_id = method_with_name(ccx, impl_id, im.ident); if has_tps { if m_id.crate != ast::local_crate { m_id = maybe_instantiate_inline(ccx, m_id); } monomorphic_fn(ccx, m_id, substs, some(vtables), none).val } else if m_id.crate == ast::local_crate { get_item_val(ccx, m_id.node) } else { trans_external_path(ccx, m_id, fty) } } })) } fn trans_cast(bcx: block, val: @ast::expr, id: ast::node_id, dest: dest) -> block { let _icx = bcx.insn_ctxt("impl::trans_cast"); if dest == ignore { return trans_expr(bcx, val, ignore); } let ccx = bcx.ccx(); let v_ty = expr_ty(bcx, val); let {bcx: bcx, box: llbox, body: body} = malloc_boxed(bcx, v_ty); add_clean_free(bcx, llbox, heap_shared); let bcx = trans_expr_save_in(bcx, val, body); revoke_clean(bcx, llbox); let result = get_dest_addr(dest); Store(bcx, llbox, PointerCast(bcx, GEPi(bcx, result, ~[0u, 1u]), T_ptr(val_ty(llbox)))); let orig = ccx.maps.vtable_map.get(id)[0]; let orig = resolve_vtable_in_fn_ctxt(bcx.fcx, orig); let vtable = get_vtable(bcx.ccx(), orig); Store(bcx, vtable, PointerCast(bcx, GEPi(bcx, result, ~[0u, 0u]), T_ptr(val_ty(vtable)))); bcx }
fn trans_method(ccx: @crate_ctxt, path: path, method: &ast::method, param_substs: option<param_substs>, llfn: ValueRef) { let self_arg = match method.self_ty.node { ast::sty_static => { no_self } _ => { let self_ty = ty::node_id_to_type(ccx.tcx, method.self_id); let self_ty = match param_substs { none => self_ty, some({tys: ref tys, _}) => ty::subst_tps(ccx.tcx, *tys, self_ty) }; match method.self_ty.node { ast::sty_value => { impl_owned_self(self_ty) } _ => { impl_self(self_ty) } } } }; trans_fn(ccx, path, method.decl, method.body, llfn, self_arg, param_substs, method.id); }
function_block-full_function
[ { "content": "fn val_ty(v: ValueRef) -> TypeRef { return llvm::LLVMTypeOf(v); }\n\n\n", "file_path": "src/rustc/middle/trans/common.rs", "rank": 0, "score": 566159.6927412436 }, { "content": "// LLVM constant constructors.\n\nfn C_null(t: TypeRef) -> ValueRef { return llvm::LLVMConstNull(t);...
Rust
src/dms/font.rs
mnit-rtmc/ntcip
ccc7d59869d4fc406f7f0d0550112e5b3b390bb2
use crate::dms::multi::SyntaxError; use crate::dms::Result; use log::debug; use pix::{rgb::SRgb8, Raster}; use std::collections::HashMap; #[derive(Deserialize, Serialize)] pub struct Character { number: u16, width: u8, #[serde(with = "super::base64")] bitmap: Vec<u8>, } #[derive(Deserialize, Serialize)] pub struct Font { number: u8, name: String, height: u8, char_spacing: u8, line_spacing: u8, characters: Vec<Character>, version_id: u16, } #[derive(Default)] pub struct FontCache { fonts: HashMap<u8, Font>, } impl Character { pub fn number(&self) -> u16 { self.number } pub fn width(&self) -> u8 { self.width } fn render_char( &self, page: &mut Raster<SRgb8>, x: i32, y: i32, height: i32, cf: SRgb8, ) { let width = i32::from(self.width); debug!( "render_char: {} @ {},{} width: {}", self.number, x, y, width ); let mut xx = 0; let mut yy = 0; for by in &self.bitmap { for bi in 0..8 { if by >> (7 - bi) & 1 != 0 { *page.pixel_mut(x + xx, y + yy) = cf; } xx += 1; if xx >= width { xx = 0; yy += 1; if yy >= height { break; } } } } } } impl<'a> Font { pub fn number(&self) -> u8 { self.number } pub fn name(&self) -> &str { &self.name } pub fn height(&self) -> u8 { self.height } pub fn char_spacing(&self) -> u8 { self.char_spacing } pub fn line_spacing(&self) -> u8 { self.line_spacing } pub fn character(&'a self, ch: char) -> Result<&'a Character> { let code_point = u32::from(ch); if code_point <= u32::from(std::u16::MAX) { let n = code_point as u16; if let Some(c) = self.characters.iter().find(|c| c.number == n) { return Ok(c); } } Err(SyntaxError::CharacterNotDefined(ch)) } pub fn text_width(&self, text: &str, cs: Option<u16>) -> Result<u16> { let mut width = 0; let cs = cs.unwrap_or_else(|| u16::from(self.char_spacing)); for ch in text.chars() { let c = self.character(ch)?; if width > 0 { width += cs; } width += u16::from(c.width()); } Ok(width) } pub fn render_text( &self, page: &mut Raster<SRgb8>, text: &str, x: i32, y: i32, cs: i32, cf: SRgb8, ) -> Result<()> { let height = i32::from(self.height()); debug!( "render_text: font number {}, name {}", self.number(), self.name() ); debug!("render_text: {} @ {},{} height: {}", text, x, y, height); let mut xx = 0; for ch in text.chars() { let c = self.character(ch)?; if xx > 0 { xx += cs; } c.render_char(page, x + xx, y, height, cf); xx += i32::from(c.width()); } Ok(()) } pub fn version_id(&self) -> u16 { self.version_id } } impl FontCache { pub fn insert(&mut self, font: Font) { self.fonts.insert(font.number(), font); } pub fn lookup<'a>( &'a self, fnum: u8, version_id: Option<u16>, ) -> Result<&'a Font> { match (self.fonts.get(&fnum), version_id) { (Some(f), Some(vid)) => { if vid == f.version_id { Ok(f) } else { Err(SyntaxError::FontVersionID) } } (Some(f), None) => Ok(f), (None, _) => Err(SyntaxError::FontNotDefined(fnum)), } } pub fn lookup_name<'a>(&'a self, name: &str) -> Option<&'a Font> { self.fonts.values().find(|f| f.name() == name) } }
use crate::dms::multi::SyntaxError; use crate::dms::Result; use log::debug; use pix::{rgb::SRgb8, Raster}; use std::collections::HashMap; #[derive(Deserialize, Serialize)] pub struct Character { number: u16, width: u8, #[serde(with = "super::base64")] bitmap: Vec<u8>, } #[derive(Deserialize, Serialize)] pub struct Font { number: u8, name: String, height: u8, char_spacing: u8, line_spacing: u8, characters: Vec<Character>, version_id: u16, } #[derive(Default)] pub struct FontCache { fonts: HashMap<u8, Font>, } impl Character { pub fn number(&self) -> u16 { self.number } pub fn width(&self) -> u8 { self.width } fn render_char( &self, page: &mut Raster<SRgb8>, x: i32, y: i32, height: i32, cf: SRgb8, ) { let width = i32::from(self.width); debug!( "render_char: {} @ {},{} width: {}", self.number, x, y, width ); let mut xx = 0; let mut yy = 0; for by in &self.bitmap { for bi in 0..8 { if by >> (7 - bi) & 1 != 0 { *page.pixel_mut(x + xx, y + yy) = cf; } xx += 1; if xx >= width { xx = 0; yy += 1; if yy >= height { break; } } } } } } impl<'a> Font { pub fn number(&self) -> u8 { self.number } pub fn name(&self) -> &str { &self.name } pub fn height(&self) -> u8 { self.height } pub fn char_spacing(&self) -> u8 { self.char_spacing } pub fn line_spacing(&self) -> u8 { self.line_spacing } pub fn character(&'a self, ch: char) -> Result<&'a Character> { let code_point = u32::from(ch); if code_point <= u32::from(std::u16::MAX) { let n = code_point as u16; if let Some(c) = self.characters.iter().find(|c| c.number == n) { return Ok(c); } } Err(SyntaxError::CharacterNotDefined(ch)) } pub fn text_width(&self, text: &str, cs: Option<u16>) -> Result<u16> { let mut width = 0; let cs = cs.unwrap_or_else(|| u16::from(self.char_spacing)); for ch in text.chars() { let c = self.character(ch)?; if width > 0 { width += cs; } width += u16::from(c.width()); } Ok(width) } pub fn render_text( &self, page: &mut Raster<SRgb8>,
pub fn version_id(&self) -> u16 { self.version_id } } impl FontCache { pub fn insert(&mut self, font: Font) { self.fonts.insert(font.number(), font); } pub fn lookup<'a>( &'a self, fnum: u8, version_id: Option<u16>, ) -> Result<&'a Font> { match (self.fonts.get(&fnum), version_id) { (Some(f), Some(vid)) => { if vid == f.version_id { Ok(f) } else { Err(SyntaxError::FontVersionID) } } (Some(f), None) => Ok(f), (None, _) => Err(SyntaxError::FontNotDefined(fnum)), } } pub fn lookup_name<'a>(&'a self, name: &str) -> Option<&'a Font> { self.fonts.values().find(|f| f.name() == name) } }
text: &str, x: i32, y: i32, cs: i32, cf: SRgb8, ) -> Result<()> { let height = i32::from(self.height()); debug!( "render_text: font number {}, name {}", self.number(), self.name() ); debug!("render_text: {} @ {},{} height: {}", text, x, y, height); let mut xx = 0; for ch in text.chars() { let c = self.character(ch)?; if xx > 0 { xx += cs; } c.render_char(page, x + xx, y, height, cf); xx += i32::from(c.width()); } Ok(()) }
function_block-function_prefix_line
[ { "content": "/// Normalize a MULTI string.\n\npub fn normalize(ms: &str) -> String {\n\n let mut s = String::with_capacity(ms.len());\n\n for t in Parser::new(ms) {\n\n if let Ok(v) = t {\n\n s.push_str(&v.to_string());\n\n }\n\n }\n\n s\n\n}\n\n\n\n#[cfg(test)]\n\nmod test...
Rust
rust/src/methods/reshape/mod.rs
stencila/stencila
bff4faceb1460a84b096e9e45f4a4580a0156295
use super::decode::date::decode_date_maybe; use super::decode::person::decode_person; use super::encode::txt::ToTxt; use defaults::Defaults; use eyre::Result; use once_cell::sync::Lazy; use regex::Regex; use stencila_schema::{ Article, BlockContent, CreativeWorkAuthors, CreativeWorkTitle, Date, InlineContent, Node, Paragraph, Person, ThingDescription, }; #[derive(Defaults)] pub struct Options { #[def = "true"] article: bool, #[def = "true"] detect_title: bool, #[def = "true"] infer_title: bool, #[def = "true"] detect_authors: bool, #[def = "true"] infer_authors: bool, #[def = "true"] detect_date: bool, #[def = "true"] infer_date: bool, #[def = "true"] detect_keywords: bool, #[def = "true"] detect_abstract: bool, } pub fn reshape(node: &mut Node, options: Options) -> Result<()> { if let (Node::Article(article), true) = (node, &options.article) { reshape_article(article, &options) } Ok(()) } pub fn reshape_article(article: &mut Article, options: &Options) { if let Some(blocks) = &mut article.content { let mut index = 0; while index < blocks.len() { let mut delta = 1; if index == 0 { if article.title.is_none() && options.detect_title { delta += detect_title(&mut article.title, blocks, index) } if !blocks.is_empty() && article.title.is_none() && options.infer_title { delta += infer_title(&mut article.title, blocks, index) } if !blocks.is_empty() && article.authors.is_none() && options.detect_authors { delta += detect_authors(&mut article.authors, blocks, index) } if !blocks.is_empty() && article.authors.is_none() && options.infer_authors { delta += infer_authors(&mut article.authors, blocks, index) } if !blocks.is_empty() && article.date_modified.is_none() && options.detect_date { delta += detect_date(&mut article.date_modified, blocks, index) } if !blocks.is_empty() && article.date_modified.is_none() && options.infer_date { delta += infer_date(&mut article.date_modified, blocks, index) } if !blocks.is_empty() && article.keywords.is_none() && options.detect_keywords { delta += detect_keywords(&mut article.keywords, blocks, index) } if !blocks.is_empty() && article.description.is_none() && options.detect_abstract { delta += detect_abstract(&mut article.description, blocks, index) } } index = index.saturating_add(delta.max(0) as usize); } } } fn first_is_strong(paragraph: &Paragraph) -> bool { matches!(paragraph.content.first(), Some(InlineContent::Strong(_))) } fn first_is_emphasis(paragraph: &Paragraph) -> bool { matches!(paragraph.content.first(), Some(InlineContent::Emphasis(_))) } fn has_superscript(paragraph: &Paragraph) -> bool { paragraph .content .iter() .any(|inline| matches!(inline, InlineContent::Superscript(_))) } fn remove_first_mark(paragraph: &Paragraph) -> Vec<InlineContent> { let mut content = match paragraph.content.first() { Some(InlineContent::Emphasis(emphasis)) => emphasis.content.clone(), Some(InlineContent::Strong(strong)) => strong.content.clone(), _ => Vec::new(), }; let mut rest = paragraph.content.clone(); rest.remove(0); content.append(&mut rest); content } fn detect_title( title: &mut Option<Box<CreativeWorkTitle>>, blocks: &mut Vec<BlockContent>, index: usize, ) -> i32 { static BEGINS_REGEX: Lazy<Regex> = Lazy::new(|| { Regex::new("^(?:T|t)itle\\b(?:[^\\w]*)?(.*)").expect("Unable to create regex") }); if let BlockContent::Paragraph(paragraph) = &blocks[index] { let txt = paragraph.to_txt(); if let Some(captures) = BEGINS_REGEX.captures(&txt) { *title = Some(Box::new(CreativeWorkTitle::VecInlineContent(vec![ InlineContent::String(captures[1].to_string()), ]))); blocks.remove(index); return -1; } } 0 } fn infer_title( title: &mut Option<Box<CreativeWorkTitle>>, blocks: &mut Vec<BlockContent>, index: usize, ) -> i32 { let inferred = match &blocks[index] { BlockContent::Heading(heading) => { if heading.depth == Some(1) { Some(Box::new(CreativeWorkTitle::VecInlineContent( heading.content.clone(), ))) } else { None } } BlockContent::Paragraph(paragraph) => { if first_is_strong(paragraph) || first_is_emphasis(paragraph) { Some(Box::new(CreativeWorkTitle::VecInlineContent( remove_first_mark(paragraph), ))) } else { None } } _ => None, }; if inferred.is_some() { *title = inferred; blocks.remove(index); -1 } else { 0 } } fn detect_authors( authors: &mut Option<Vec<CreativeWorkAuthors>>, blocks: &mut Vec<BlockContent>, index: usize, ) -> i32 { static BEGINS_REGEX: Lazy<Regex> = Lazy::new(|| { Regex::new("^(?:A|a)uthors?\\b(?:[^\\w]*)?(.*)").expect("Unable to create regex") }); static SPLIT_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new("\\s*;|(and)|&\\s*").expect("Unable to create regex")); if let BlockContent::Paragraph(paragraph) = &blocks[index] { let txt = paragraph.to_txt(); if let Some(captures) = BEGINS_REGEX.captures(&txt) { let authors_ = SPLIT_REGEX .split(&captures[1]) .map(|str| CreativeWorkAuthors::Person(decode_person(str))) .collect(); *authors = Some(authors_); blocks.remove(index); return -1; } } 0 } fn infer_authors( authors: &mut Option<Vec<CreativeWorkAuthors>>, blocks: &mut Vec<BlockContent>, index: usize, ) -> i32 { let inferred = match &blocks[index] { BlockContent::Paragraph(paragraph) => { if has_superscript(paragraph) { Some(vec![CreativeWorkAuthors::Person(Person { name: Some(Box::new("superscripted".to_string())), ..Default::default() })]) } else { None } } _ => None, }; if inferred.is_some() { *authors = inferred; blocks.remove(index); -1 } else { 0 } } fn detect_date(date: &mut Option<Box<Date>>, blocks: &mut Vec<BlockContent>, index: usize) -> i32 { static BEGINS_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new("^(?:D|d)ate\\b(?:[^\\w]*)?(.*)").expect("Unable to create regex")); if let BlockContent::Paragraph(paragraph) = &blocks[index] { let txt = paragraph.to_txt(); if let Some(captures) = BEGINS_REGEX.captures(&txt) { if let Some(date_) = decode_date_maybe(&captures[1]) { *date = Some(Box::new(date_)); blocks.remove(index); return -1; } } } 0 } fn infer_date(date: &mut Option<Box<Date>>, blocks: &mut Vec<BlockContent>, index: usize) -> i32 { if let BlockContent::Paragraph(paragraph) = &blocks[index] { let txt = paragraph.to_txt(); if let Some(date_) = decode_date_maybe(&txt) { *date = Some(Box::new(date_)); blocks.remove(index); return -1; } } 0 } fn detect_keywords( keywords: &mut Option<Vec<String>>, blocks: &mut Vec<BlockContent>, index: usize, ) -> i32 { static BEGINS_REGEX: Lazy<Regex> = Lazy::new(|| { Regex::new("^(?:K|k)eywords?\\b(?:[^\\w]*)?(.*)").expect("Unable to create regex") }); static SPLIT_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new("\\s*;|,\\s*").expect("Unable to create regex")); if let BlockContent::Paragraph(paragraph) = &blocks[index] { let txt = paragraph.to_txt(); if let Some(captures) = BEGINS_REGEX.captures(&txt) { let keywords_ = SPLIT_REGEX .split(&captures[1]) .map(|str| str.to_string()) .collect(); *keywords = Some(keywords_); blocks.remove(index); return -1; } } 0 } fn detect_abstract( abstract_: &mut Option<Box<ThingDescription>>, blocks: &mut Vec<BlockContent>, index: usize, ) -> i32 { let is_abstract = match &blocks[index] { BlockContent::Heading(heading) => { let txt = heading.to_txt(); txt.trim() == "Abstract" } BlockContent::Paragraph(paragraph) => { let txt = paragraph.to_txt(); txt.trim() == "Abstract" } _ => false, }; if !is_abstract { return 0; } blocks.remove(index); let mut removed = 1; let mut content: Vec<BlockContent> = Vec::new(); while index < blocks.len() { let next = &blocks[index]; match next { BlockContent::Paragraph(_) => { content.push(next.clone()); blocks.remove(index); removed += 1; } _ => break, } } *abstract_ = Some(Box::new(ThingDescription::VecBlockContent(content))); -removed } #[cfg(test)] mod tests { use super::*; use crate::methods::decode::yaml; use crate::utils::tests::snapshot_fixtures; use insta::assert_json_snapshot; #[test] fn reshape_yaml_articles() { snapshot_fixtures("articles/reshape-*.yaml", |_path, content| { let mut article = yaml::decode(&content).expect("Unable to decode YAML"); reshape(&mut article, Options::default()).expect("Unable to reshape"); assert_json_snapshot!(article); }); } }
use super::decode::date::decode_date_maybe; use super::decode::person::decode_person; use super::encode::txt::ToTxt; use defaults::Defaults; use eyre::Result; use once_cell::sync::Lazy; use regex::Regex; use stencila_schema::{ Article, BlockContent, CreativeWorkAuthors, CreativeWorkTitle, Date, InlineContent, Node, Paragraph, Person, ThingDescription, }; #[derive(Defaults)] pub struct Options { #[def = "true"] article: bool, #[def = "true"] detect_title: bool, #[def = "true"] infer_title: bool, #[def = "true"] detect_authors: bool, #[def = "true"] infer_authors: bool, #[def = "true"] detect_date: bool, #[def = "true"] infer_date: bool, #[def = "true"] detect_keywords: bool, #[def = "true"] detect_abstract: bool, } pub fn reshape(node: &mut Node, options: Options) -> Result<()> { if let (Node::Article(article), true) = (node, &options.article) { reshape_article(article, &options) } Ok(()) } pub fn reshape_article(article: &mut Article, options: &Options) { if let Some(blocks) = &mut article.content { let mut index = 0; while index < blocks.len() { let mut delta = 1; if index == 0 { if article.title.is_none() && options.detect_title { delta += detect_title(&mut article.title, blocks, index) } if !blocks.is_empty() && article.title.is_none() && options.infer_title { delta += infer_title(&mut article.title, blocks, index) } if !blocks.is_empty() && article.authors.is_none() && options.detect_authors { delta += detect_authors(&mut article.authors, blocks, index) } if !blocks.is_empty() && article.authors.is_none() && options.infer_authors { delta += infer_authors(&mut article.authors, blocks, index) } if !blocks.is_empty() && article.date_modified.is_none() && options.detect_date { delta += detect_date(&mut article.date_modified, blocks, index) } if !blocks.is_empty() && article.date_modified.is_none() && options.infer_date { delta += infer_date(&mut article.date_modified, blocks, index) } if !blocks.is_empty() && article.keywords.is_none() && options.detect_keywords { delta += detect_keywords(&mut article.keywords, blocks, index) } if !blocks.is_empty() && article.description.is_none() && options.detect_abstract { delta += detect_abstract(&mut article.description, blocks, index) } } index = index.saturating_add(delta.max(0) as usize); } } } fn first_is_strong(paragraph: &Paragraph) -> bool { matches!(paragraph.content.first(), Some(InlineContent::Strong(_))) } fn first_is_emphasis(paragraph: &Paragraph) -> bool { matches!(paragraph.content.first(), Some(InlineContent::Emphasis(_))) } fn has_superscript(paragraph: &Paragraph) -> bool { paragraph .content .iter() .any(|inline| matches!(inline, InlineContent::Superscript(_))) } fn remove_first_mark(paragraph: &Paragraph) -> Vec<InlineContent> { let mut content = match paragraph.content.first() { Some(InlineContent::Emphasis(emphasis)) => emphasis.content.clone(), Some(InlineContent::Strong(strong)) => strong.content.clone(), _ => Vec::new(), }; let mut rest = paragraph.content.clone(); rest.remove(0); content.append(&mut rest); content } fn detect_title( title: &mut Option<Box<CreativeWorkTitle>>, blocks: &mut Vec<BlockContent>, index: usize, ) -> i32 { static BEGINS_REGEX: Lazy<Regex> = Lazy::new(|| { Regex::new("^(?:T|t)itle\\b(?:[^\\w]*)?(.*)").expect("Unable to create regex") }); if let BlockContent::Paragraph(paragraph) = &blocks[index] { let txt = paragraph.to_txt(); if let Some(captures) = BEGINS_REGEX.captures(&txt) { *title = Some(Box::new(CreativeWorkTitle::VecInlineContent(vec![ InlineContent::String(captures[1].to_string()), ]))); blocks.remove(index); return -1; } } 0 } fn infer_title( title: &mut Option<Box<CreativeWorkTitle>>, blocks: &mut Vec<BlockContent>, index: usize, ) -> i32 { let inferred = match &blocks[index] { BlockContent::Heading(heading) => { if heading.depth == Some(1) { Some(Box::new(CreativeWorkTitle::VecInlineContent( heading.content.clone(), ))) } else { None } } BlockContent::Paragraph(paragraph) => { if first_is_strong(paragraph) || first_is_emphasis(paragraph) { Some(Box::new(CreativeWorkTitle::VecInlineContent( remove_first_mark(paragraph), ))) } else { None } } _ => None, }; if inferred.is_some() { *title = inferred; blocks.remove(index); -1 } else { 0 } } fn detect_authors( authors: &mut Option<Vec<CreativeWorkAuthors>>, blocks: &mut Vec<BlockContent>, index: usize, ) -> i32 { static BEGINS_REGEX: Lazy<Regex> = Lazy::new(|| { Regex::new("^(?:A|a)uthors?\\b(?:[^\\w]*)?(.*)").expect("Unable to create r
BEGINS_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new("^(?:D|d)ate\\b(?:[^\\w]*)?(.*)").expect("Unable to create regex")); if let BlockContent::Paragraph(paragraph) = &blocks[index] { let txt = paragraph.to_txt(); if let Some(captures) = BEGINS_REGEX.captures(&txt) { if let Some(date_) = decode_date_maybe(&captures[1]) { *date = Some(Box::new(date_)); blocks.remove(index); return -1; } } } 0 } fn infer_date(date: &mut Option<Box<Date>>, blocks: &mut Vec<BlockContent>, index: usize) -> i32 { if let BlockContent::Paragraph(paragraph) = &blocks[index] { let txt = paragraph.to_txt(); if let Some(date_) = decode_date_maybe(&txt) { *date = Some(Box::new(date_)); blocks.remove(index); return -1; } } 0 } fn detect_keywords( keywords: &mut Option<Vec<String>>, blocks: &mut Vec<BlockContent>, index: usize, ) -> i32 { static BEGINS_REGEX: Lazy<Regex> = Lazy::new(|| { Regex::new("^(?:K|k)eywords?\\b(?:[^\\w]*)?(.*)").expect("Unable to create regex") }); static SPLIT_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new("\\s*;|,\\s*").expect("Unable to create regex")); if let BlockContent::Paragraph(paragraph) = &blocks[index] { let txt = paragraph.to_txt(); if let Some(captures) = BEGINS_REGEX.captures(&txt) { let keywords_ = SPLIT_REGEX .split(&captures[1]) .map(|str| str.to_string()) .collect(); *keywords = Some(keywords_); blocks.remove(index); return -1; } } 0 } fn detect_abstract( abstract_: &mut Option<Box<ThingDescription>>, blocks: &mut Vec<BlockContent>, index: usize, ) -> i32 { let is_abstract = match &blocks[index] { BlockContent::Heading(heading) => { let txt = heading.to_txt(); txt.trim() == "Abstract" } BlockContent::Paragraph(paragraph) => { let txt = paragraph.to_txt(); txt.trim() == "Abstract" } _ => false, }; if !is_abstract { return 0; } blocks.remove(index); let mut removed = 1; let mut content: Vec<BlockContent> = Vec::new(); while index < blocks.len() { let next = &blocks[index]; match next { BlockContent::Paragraph(_) => { content.push(next.clone()); blocks.remove(index); removed += 1; } _ => break, } } *abstract_ = Some(Box::new(ThingDescription::VecBlockContent(content))); -removed } #[cfg(test)] mod tests { use super::*; use crate::methods::decode::yaml; use crate::utils::tests::snapshot_fixtures; use insta::assert_json_snapshot; #[test] fn reshape_yaml_articles() { snapshot_fixtures("articles/reshape-*.yaml", |_path, content| { let mut article = yaml::decode(&content).expect("Unable to decode YAML"); reshape(&mut article, Options::default()).expect("Unable to reshape"); assert_json_snapshot!(article); }); } }
egex") }); static SPLIT_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new("\\s*;|(and)|&\\s*").expect("Unable to create regex")); if let BlockContent::Paragraph(paragraph) = &blocks[index] { let txt = paragraph.to_txt(); if let Some(captures) = BEGINS_REGEX.captures(&txt) { let authors_ = SPLIT_REGEX .split(&captures[1]) .map(|str| CreativeWorkAuthors::Person(decode_person(str))) .collect(); *authors = Some(authors_); blocks.remove(index); return -1; } } 0 } fn infer_authors( authors: &mut Option<Vec<CreativeWorkAuthors>>, blocks: &mut Vec<BlockContent>, index: usize, ) -> i32 { let inferred = match &blocks[index] { BlockContent::Paragraph(paragraph) => { if has_superscript(paragraph) { Some(vec![CreativeWorkAuthors::Person(Person { name: Some(Box::new("superscripted".to_string())), ..Default::default() })]) } else { None } } _ => None, }; if inferred.is_some() { *authors = inferred; blocks.remove(index); -1 } else { 0 } } fn detect_date(date: &mut Option<Box<Date>>, blocks: &mut Vec<BlockContent>, index: usize) -> i32 { static
random
[ { "content": "/// Decode any front matter in a Markdown document into a `Node`\n\n///\n\n/// Any front matter will be coerced into a `Node`, defaulting to the\n\n/// `Node::Article` variant, if `type` is not defined.\n\n/// If there is no front matter detected, will return `None`.\n\npub fn decode_frontmatter(m...
Rust
db/src/models/group.rs
davedray/gatekeeper
0292c33941ec08da2f6e5514b70b9c80fd74ea47
use chrono::{DateTime, Utc}; use diesel::{AsChangeset, Insertable, Queryable}; use serde::{Deserialize, Serialize}; use uuid::Uuid; use crate::models::{Realm, Role, User}; use crate::schema::{groups, groups_roles, users_groups}; #[derive(Insertable, Identifiable, Queryable, Associations, Serialize, Deserialize, PartialEq, Debug, Clone)] #[belongs_to(Realm, foreign_key = "realm_id")] pub struct Group { pub id: Uuid, pub realm_id: Uuid, pub name: String, pub description: String, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, } #[derive(Identifiable, Insertable, Queryable, Associations, Serialize, Deserialize, PartialEq, Debug, Clone)] #[belongs_to(Group, foreign_key = "group_id")] #[belongs_to(User, foreign_key = "user_id")] #[primary_key(user_id, group_id)] #[table_name="users_groups"] pub struct GroupUser { pub group_id: Uuid, pub user_id: Uuid, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, } #[derive(Identifiable, Serialize, Deserialize, PartialEq, Debug, Clone)] #[primary_key(user_id, group_id)] #[table_name="users_groups"] pub struct DeleteGroupUser { pub group_id: Uuid, pub user_id: Uuid, } #[derive(Identifiable, Insertable, Queryable, Associations, Serialize, Deserialize, PartialEq, Debug, Clone)] #[belongs_to(Group, foreign_key = "group_id")] #[belongs_to(Role, foreign_key = "role_id")] #[primary_key(group_id, role_id)] #[table_name="groups_roles"] pub struct GroupRole { pub group_id: Uuid, pub role_id: Uuid, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, } #[derive(Identifiable, Serialize, Deserialize, PartialEq, Debug, Clone)] #[primary_key(group_id, role_id)] #[table_name="groups_roles"] pub struct DeleteGroupRole { pub group_id: Uuid, pub role_id: Uuid, } impl GroupUser { pub fn from(a: domain::AddUserToGroup) -> Self { Self { user_id: a.user_id, group_id: a.group_id, created_at: Utc::now(), updated_at: Utc::now(), } } } impl From<domain::RemoveUserFromGroup> for DeleteGroupUser { fn from(a: domain::RemoveUserFromGroup) -> Self { Self { user_id: a.user_id, group_id: a.group_id, } } } impl GroupRole { pub fn from(a: domain::AddRoleToGroup) -> Self { Self { role_id: a.role_id, group_id: a.group_id, created_at: Utc::now(), updated_at: Utc::now(), } } } impl From<domain::RemoveRoleFromGroup> for DeleteGroupRole { fn from(a: domain::RemoveRoleFromGroup) -> Self { Self { role_id: a.role_id, group_id: a.group_id, } } } impl From<Group> for domain::Group { fn from(a: Group) -> Self { domain::Group::new( a.id, a.realm_id, a.name, a.description, a.created_at, a.updated_at, ) } } #[derive(AsChangeset)] #[table_name = "groups"] pub struct UpdateGroup { pub id: Uuid, pub name: Option<String>, pub description: Option<String>, pub updated_at: DateTime<Utc>, } impl Group { pub fn from(a: domain::AddRealmGroup) -> Self { Self { id: Uuid::new_v4(), realm_id: a.realm_id, name: a.name, description: a.description, created_at: Utc::now(), updated_at: Utc::now(), } } } impl UpdateGroup { pub fn from(a: domain::UpdateGroup) -> Self { Self { id: a.id, name: a.name, description: a.description, updated_at: Utc::now(), } } }
use chrono::{DateTime, Utc}; use diesel::{AsChangeset, Insertable, Queryable}; use serde::{Deserialize, Serialize}; use uuid::Uuid; use crate::models::{Realm, Role, User}; use crate::schema::{groups, groups_roles, users_groups}; #[derive(Insertable, Identifiable, Queryable, Associations, Serialize, Deserialize, PartialEq, Debug, Clone)] #[belongs_to(Realm, foreign_key = "realm_id")] pub struct Group { pub id: Uuid, pub realm_id: Uuid, pub name: String, pub description: String, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, } #[derive(Identifiable, Insertable, Queryable, Associations, Serialize, Deserialize, PartialEq, Debug, Clone)] #[belongs_to(Group, foreign_key = "group_id")] #[belongs_to(User, foreign_key = "user_id")] #[primary_key(user_id, group_id)] #[table_name="users_groups"] pub struct GroupUser { pub group_id: Uuid, pub user_id: Uuid, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, } #[derive(Identifiable, Serialize, Deserialize, PartialEq, Debug, Clone)] #[primary_key(user_id, group_id)] #[table_name="users_groups"] pub struct DeleteGroupUser { pub group_id: Uuid, pub user_id: Uuid, } #[derive(Identifiable, Insertable, Queryable, Associations, Serialize, Deserialize, PartialEq, Debug, Clone)] #[belongs_to(Group, foreign_key = "group_id")] #[belongs_to(Role, foreign_key = "role_id")] #[primary_key(group_id, role_id)] #[table_name="groups_roles"] pub struct GroupRole { pub group_id: Uuid, pub role_id: Uuid, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, } #[derive(Identifiable, Serialize, Deserialize, PartialEq, Debug, Clone)] #[primary_key(group_id, role_id)] #[table_name="groups_roles"] pub struct DeleteGroupRole { pub group_id: Uuid, pub role_id: Uuid, } impl GroupUser { pub fn from(a: domain::AddUserToGroup) -> Self { Self { user_id: a.user_id, group_id: a.group_id, created_at: Utc::now(), updated_at: Utc::now(), } } } impl From<domain::RemoveUserFromGroup> for DeleteGroupUser { fn from(a: domain::RemoveUserFromGroup) -> Self { Self { user_id: a.user_id, group_id: a.group_id, } } } impl GroupRole { pub fn from(a: domain::AddRoleToGroup) -> Self { Self { role_id: a.role_id, group_id: a.group_id, created_at: Utc::now(), updated_at: Utc::now(), } } } impl From<domain::RemoveRoleFromGroup> for DeleteGroupRole {
} impl From<Group> for domain::Group { fn from(a: Group) -> Self { domain::Group::new( a.id, a.realm_id, a.name, a.description, a.created_at, a.updated_at, ) } } #[derive(AsChangeset)] #[table_name = "groups"] pub struct UpdateGroup { pub id: Uuid, pub name: Option<String>, pub description: Option<String>, pub updated_at: DateTime<Utc>, } impl Group { pub fn from(a: domain::AddRealmGroup) -> Self { Self { id: Uuid::new_v4(), realm_id: a.realm_id, name: a.name, description: a.description, created_at: Utc::now(), updated_at: Utc::now(), } } } impl UpdateGroup { pub fn from(a: domain::UpdateGroup) -> Self { Self { id: a.id, name: a.name, description: a.description, updated_at: Utc::now(), } } }
fn from(a: domain::RemoveRoleFromGroup) -> Self { Self { role_id: a.role_id, group_id: a.group_id, } }
function_block-full_function
[ { "content": "pub fn ids_by_group(repo: &Postgres, group: Uuid) -> Result<Vec<Uuid>, Error> {\n\n use crate::schema::groups_roles::dsl::*;\n\n groups_roles.filter(group_id.eq(group)).select(role_id).load(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/roles.rs", "rank": 0, "score": 291...
Rust
src/parser/storage.rs
marirs/msg-parser-rs
cd508394d9a98d22e2b7c0d851bfe36ca6a0d464
use std::{ collections::HashMap, u32::MAX, }; use hex::decode; use crate::ole::{Entry, EntryType, Reader}; use super::{ constants::PropIdNameMap, decode::DataType, stream::Stream }; #[derive(Debug, Clone, PartialEq)] pub enum StorageType { Recipient(u32), Attachment(u32), RootEntry, } impl StorageType { fn convert_id_to_u32(id: &str) -> Option<u32> { if id.len() != 8 { return None; } let decoded = decode(id).ok()?; let mut base = 1u32; let mut sum = 0u32; for &num in decoded.iter().rev() { sum = sum + num as u32 * base; if base >= MAX / 256 { break; } base *= 256; } Some(sum) } pub fn create(name: &str) -> Option<Self> { if name.starts_with("__recip_version1.0_") { let id = name.split("#").collect::<Vec<&str>>()[1]; let id_as_num = StorageType::convert_id_to_u32(id)?; return Some(StorageType::Recipient(id_as_num)); } if name.starts_with("__attach_version1.0_") { let id = name.split("#").collect::<Vec<&str>>()[1]; let id_as_num = StorageType::convert_id_to_u32(id)?; return Some(StorageType::Attachment(id_as_num)); } None } } #[derive(Debug)] struct EntryStorageMap { map: HashMap<u32, StorageType>, } impl EntryStorageMap { pub fn new(parser: &Reader) -> Self { let mut storage_map: HashMap<u32, StorageType> = HashMap::new(); for entry in parser.iterate() { match entry._type() { EntryType::RootStorage => { storage_map.insert(entry.id(), StorageType::RootEntry); } EntryType::UserStorage => { StorageType::create(entry.name()) .and_then(|storage| storage_map.insert(entry.id(), storage)); } _ => { continue; } } } Self { map: storage_map } } pub fn get_storage_type(&self, parent_id: Option<u32>) -> Option<&StorageType> { self.map.get(&parent_id?) } } pub type Properties = HashMap<String, DataType>; pub type Recipients = Vec<Properties>; pub type Attachments = Vec<Properties>; #[derive(Debug)] pub struct Storages { storage_map: EntryStorageMap, prop_map: PropIdNameMap, pub attachments: Attachments, pub recipients: Recipients, pub root: Properties, } impl Storages { fn to_arr(map: HashMap<u32, Properties>) -> Vec<Properties> { let mut tuples: Vec<(u32, Properties)> = map .into_iter() .map(|(k, v)| (k, v)) .collect::<Vec<(u32, Properties)>>(); tuples.sort_by(|a, b| a.0.cmp(&b.0)); tuples.into_iter().map(|x| x.1).collect::<Vec<Properties>>() } fn create_stream(&self, parser: &Reader, entry: &Entry) -> Option<Stream> { let parent = self.storage_map.get_storage_type(entry.parent_node())?; let mut slice = parser.get_entry_slice(entry).ok()?; Stream::create(entry.name(), &mut slice, &self.prop_map, parent) } pub fn process_streams(&mut self, parser: &Reader) { let mut recipients_map: HashMap<u32, Properties> = HashMap::new(); let mut attachments_map: HashMap<u32, Properties> = HashMap::new(); for entry in parser.iterate() { if let EntryType::UserStream = entry._type() { let stream_res = self.create_stream(&parser, &entry); if stream_res.is_none() { continue; } let stream = stream_res.unwrap(); match stream.parent { StorageType::RootEntry => { self.root.insert(stream.key, stream.value); } StorageType::Recipient(id) => { let recipient_map = recipients_map.entry(id).or_insert(HashMap::new()); (*recipient_map).insert(stream.key, stream.value); } StorageType::Attachment(id) => { let attachment_map = attachments_map.entry(id).or_insert(HashMap::new()); (*attachment_map).insert(stream.key, stream.value); } } } } self.recipients = Self::to_arr(recipients_map); self.attachments = Self::to_arr(attachments_map); } pub fn new(parser: &Reader) -> Self { let root: Properties = HashMap::new(); let recipients: Recipients = vec![]; let attachments: Attachments = vec![]; let storage_map = EntryStorageMap::new(parser); let prop_map = PropIdNameMap::init(); Self { storage_map, prop_map, root, recipients, attachments, } } pub fn get_val_from_root_or_default(&self, key: &str) -> String { self.root.get(key).map_or(String::new(), |x| x.into()) } pub fn get_val_from_attachment_or_default(&self, idx: usize, key: &str) -> String { self.attachments .iter() .nth(idx) .map(|attach| attach.get(key).map_or(String::from(""), |x| x.into())) .unwrap_or(String::new()) } } #[cfg(test)] mod tests { use super::super::decode::DataType; use super::{EntryStorageMap, Properties, StorageType, Storages}; use crate::ole::Reader; use std::collections::HashMap; #[test] fn test_storage_type_convert() { use std::u32::MAX; let mut id = StorageType::convert_id_to_u32("00000001"); assert_eq!(id, Some(1u32)); id = StorageType::convert_id_to_u32("0000000A"); assert_eq!(id, Some(10u32)); id = StorageType::convert_id_to_u32("00000101"); assert_eq!(id, Some(257u32)); id = StorageType::convert_id_to_u32("FFFFFFFF"); assert_eq!(id, Some(MAX)); id = StorageType::convert_id_to_u32("HELLO"); assert_eq!(id, None); id = StorageType::convert_id_to_u32("00000000000000"); assert_eq!(id, None); } #[test] fn test_create_storage_type() { let recipient = StorageType::create("__recip_version1.0_#0000000A"); assert_eq!(recipient, Some(StorageType::Recipient(10))); let attachment = StorageType::create("__attach_version1.0_#0000000A"); assert_eq!(attachment, Some(StorageType::Attachment(10))); let unknown_storage = StorageType::create(""); assert_eq!(unknown_storage, None); } #[test] fn test_storage_map() { let parser = Reader::from_path("data/test_email.msg").unwrap(); let storage_map = EntryStorageMap::new(&parser); let mut expected_map = HashMap::new(); expected_map.insert(0, StorageType::RootEntry); expected_map.insert(73, StorageType::Recipient(0)); expected_map.insert(85, StorageType::Recipient(1)); expected_map.insert(97, StorageType::Recipient(2)); expected_map.insert(108, StorageType::Recipient(3)); expected_map.insert(120, StorageType::Recipient(4)); expected_map.insert(132, StorageType::Recipient(5)); expected_map.insert(143, StorageType::Attachment(0)); expected_map.insert(260, StorageType::Recipient(0)); expected_map.insert(310, StorageType::Attachment(1)); expected_map.insert(323, StorageType::Attachment(2)); assert_eq!(storage_map.map, expected_map); } #[test] fn test_storage_to_arr() { let mut map_apple: Properties = HashMap::new(); map_apple.insert("A".to_string(), DataType::PtypString("Apple".to_string())); let mut map_bagel: Properties = HashMap::new(); map_bagel.insert("B".to_string(), DataType::PtypString("Bagel".to_string())); let mut basket: HashMap<u32, Properties> = HashMap::new(); basket.insert(1, map_apple); basket.insert(0, map_bagel); let res = Storages::to_arr(basket); assert_eq!( res[0].get("B"), Some(&DataType::PtypString("Bagel".to_string())) ); assert_eq!( res[1].get("A"), Some(&DataType::PtypString("Apple".to_string())) ); } #[test] fn test_create_storage_test_email() { let parser = Reader::from_path("data/test_email.msg").unwrap(); let mut storages = Storages::new(&parser); storages.process_streams(&parser); let sender = storages.root.get("SenderEmailAddress"); assert!(sender.is_none()); assert_eq!(storages.attachments.len(), 3); assert_eq!(storages.recipients.len(), 6); let display_name = storages.recipients[0].get("DisplayName").unwrap(); assert_eq!( display_name, &DataType::PtypString("marirs@outlook.com".to_string()) ); } #[test] fn test_create_storage_outlook_attachments() { let parser = Reader::from_path("data/test_email.msg").unwrap(); let mut storages = Storages::new(&parser); storages.process_streams(&parser); assert_eq!(storages.attachments.len(), 3); let attachment_name = storages.attachments[0].get("DisplayName"); assert_eq!( attachment_name, Some(&DataType::PtypString("1 Days Left\u{14} 35% off cloud space, upgrade now!".to_string())) ); let attachment_name = storages.attachments[1].get("AttachFilename"); assert_eq!( attachment_name, Some(&DataType::PtypString("milky-~1.jpg".to_string())) ); let attachment_name = storages.attachments[2].get("AttachFilename"); assert_eq!( attachment_name, Some(&DataType::PtypString("TestEm~1.msg".to_string())) ); assert_eq!(storages.recipients.len(), 6); let display_name = storages.recipients[1].get("DisplayName").unwrap(); assert_eq!(display_name, &DataType::PtypString("Sriram Govindan".to_string())); } }
use std::{ collections::HashMap, u32::MAX, }; use hex::decode; use crate::ole::{Entry, EntryType, Reader}; use super::{ constants::PropIdNameMap, decode::DataType, stream::Stream }; #[derive(Debug, Clone, PartialEq)] pub enum StorageType { Recipient(u32), Attachment(u32), RootEntry, } impl StorageType { fn convert_id_to_u32(id: &str) -> Option<u32> { if id.len() != 8 { return None; } let decoded = decode(id).ok()?; let mut base = 1u32; let mut sum = 0u32; for &num in decoded.iter().rev() { sum = sum + num as u32 * base; if base >= MAX / 256 { break; } base *= 256; } Some(sum) } pub fn create(name: &str) -> Option<Self> { if name.starts_with("__recip_version1.0_") { let id = name.split("#").collect::<Vec<&str>>()[1]; let id_as_num = StorageType::convert_id_to_u32(id)?; return Some(StorageType::Recipient(id_as_num)); } if name.starts_with("__attach_version1.0_") { let id = name.split("#").collect::<Vec<&str>>()[1]; let id_as_num = StorageType::convert_id_to_u32(id)?; return Some(StorageType::Attachment(id_as_num)); } None } } #[derive(Debug)] struct EntryStorageMap { map: HashMap<u32, StorageType>, } impl EntryStorageMap { pub fn new(parser: &Reader) -> Self { let mut storage_map: HashMap<u32, StorageType> = HashMap::new(); for entry in parser.iterate() { match entry._type() { EntryType::RootStorage => { storage_map.insert(entry.id(), StorageType::RootEntry); } EntryType::UserStorage => { StorageType::create(entry.name()) .and_then(|storage| storage_map.insert(entry.id(), storage)); } _ => { continue; } } } Self { map: storage_map } } pub fn get_storage_type(&self, parent_id: Option<u32>) -> Option<&StorageType> { self.map.get(&parent_id?) } } pub type Properties = HashMap<String, DataType>; pub type Recipients = Vec<Properties>; pub type Attachments = Vec<Properties>; #[derive(Debug)] pub struct Storages { storage_map: EntryStorageMap, prop_map: PropIdNameMap, pub attachments: Attachments, pub recipients: Recipients, pub root: Properties, } impl Storages { fn to_arr(map: HashMap<u32, Properties>) -> Vec<Properties> { let mut tuples: Vec<(u32, Properties)> = map .into_iter() .map(|(k, v)| (k, v)) .collect::<Vec<(u32, Properties)>>(); tuples.sort_by(|a, b| a.0.cmp(&b.0)); tuples.into_iter().map(|x| x.1).collect::<Vec<Properties>>() } fn create_stream(&self, parser: &Reader, entry: &Entry) -> Option<Stream> { let parent = self.storage_map.get_storage_type(entry.parent_node())?; let mut slice = parser.get_entry_slice(entry).ok()?; Stream::create(entry.name(), &mut slice, &self.prop_map, parent) } pub fn process_streams(&mut self, parser: &Reader) { let mut recipients_map: HashMap<u32, Properties> = HashMap::new(); let mut attachments_map: HashMap<u32, Properties> = HashMap::new(); for entry in parser.iterate() { if let EntryType::UserStream = entry._type() { let stream_res = self.create_stream(&parser, &entry); if stream_res.is_none() { continue; } let stream = stream_res.unwrap(); match stream.parent { StorageType::RootEntry => { self.root.insert(stream.key, stream.value); } StorageType::Recipient(id) => { let recipient_map = recipients_map.entry(id).or_insert(HashMap::new()); (*recipient_map).insert(stream.key, stream.value); } StorageType::Attachment(id) => { let attachment_map = attachments_map.entry(id).or_insert(HashMap::new()); (*attachment_map).insert(stream.key, stream.value); } } } } self.recipients = Self::to_arr(recipients_map); self.attachments = Self::to_arr(attachments_map); } pub fn new(parser: &Reader) -> Self { let root: Properties = HashMap::new(); let recipients: Recipients = vec![]; let attachments: Attachments = vec![]; let storage_map = EntryStorageMap::new(parser); let prop_map = PropIdNameMap::init(); Self { storage_map, prop_map, root, recipients, attachments, } } pub fn get_val_from_root_or_default(&self, key: &str) -> String { self.root.get(key).map_or(String::new(), |x| x.into()) } pub fn get_val_from_attachment_or_default(&self, idx: usize, key: &str) -> String { self.attachments .iter() .nth(idx) .map(|attach| attach.get(key).map_or(String::from(""), |x| x.into())) .unwrap_or(String::new()) } } #[cfg(test)] mod tests { use super::super::decode::DataType; use super::{EntryStorageMap, Properties, StorageType, Storages}; use crate::ole::Reader; use std::collections::HashMap; #[test] fn test_storage_type_convert() { use std::u32::MAX; let mut id = StorageType::convert_id_to_u32("00000001"); assert_eq!(id, Some(1u32)); id = StorageType::convert_id_to_u32("0000000A"); assert_eq!(id, Some(10u32)); id = StorageType::convert_id_to_u32("00000101"); assert_eq!(id, Some(257u32)); id = StorageType::convert_id_to_u32("FFFFFFFF"); assert_eq!(id, Some(MAX)); id = StorageType::convert_id_to_u32("HELLO"); assert_eq!(id, None); id = StorageType::convert_id_to_u32("00000000000000"); assert_eq!(id, None); } #[test] fn test_create_storage_type() { let recipient = StorageType::create("__recip_version1.0_#0000000A"); assert_eq!(recipient, Some(StorageType::Recipient(10))); let attachment = StorageType::create("__attach_version1.0_#0000000A"); assert_eq!(attachment, Some(StorageType::Attachment(10))); let unknown_storage = StorageType::create(""); assert_eq!(unknown_storage, None); } #[test] fn test_storage_map() { let parser = Reader::from_path("data/test_email.msg").unwrap(); let storage_map = EntryStorageMap::new(&parser); let mut expected_map = HashMap::new(); expected_map.insert(0, StorageType::RootEntry); expected_map.insert(73, StorageType::Recipient(0)); expected_map.insert(85, StorageType::Recipient(1)); expected_map.insert(97, StorageType::Recipient(2)); expected_map.insert(108, StorageType::Recipient(3)); expected_map.insert(120, StorageType::Recipient(4)); expected_map.insert(132, StorageType::Recipient(5)); expected_map.insert(143, StorageType::Attachment(0)); expected_map.insert(260, StorageType::Recipient(0)); expected_map.insert(310, StorageType::Attachment(1)); expected_map.insert(323, StorageType::Attachment(2)); assert_eq!(storage_map.map, expected_map); } #[test] fn test_storage_to_arr() {
#[test] fn test_create_storage_test_email() { let parser = Reader::from_path("data/test_email.msg").unwrap(); let mut storages = Storages::new(&parser); storages.process_streams(&parser); let sender = storages.root.get("SenderEmailAddress"); assert!(sender.is_none()); assert_eq!(storages.attachments.len(), 3); assert_eq!(storages.recipients.len(), 6); let display_name = storages.recipients[0].get("DisplayName").unwrap(); assert_eq!( display_name, &DataType::PtypString("marirs@outlook.com".to_string()) ); } #[test] fn test_create_storage_outlook_attachments() { let parser = Reader::from_path("data/test_email.msg").unwrap(); let mut storages = Storages::new(&parser); storages.process_streams(&parser); assert_eq!(storages.attachments.len(), 3); let attachment_name = storages.attachments[0].get("DisplayName"); assert_eq!( attachment_name, Some(&DataType::PtypString("1 Days Left\u{14} 35% off cloud space, upgrade now!".to_string())) ); let attachment_name = storages.attachments[1].get("AttachFilename"); assert_eq!( attachment_name, Some(&DataType::PtypString("milky-~1.jpg".to_string())) ); let attachment_name = storages.attachments[2].get("AttachFilename"); assert_eq!( attachment_name, Some(&DataType::PtypString("TestEm~1.msg".to_string())) ); assert_eq!(storages.recipients.len(), 6); let display_name = storages.recipients[1].get("DisplayName").unwrap(); assert_eq!(display_name, &DataType::PtypString("Sriram Govindan".to_string())); } }
let mut map_apple: Properties = HashMap::new(); map_apple.insert("A".to_string(), DataType::PtypString("Apple".to_string())); let mut map_bagel: Properties = HashMap::new(); map_bagel.insert("B".to_string(), DataType::PtypString("Bagel".to_string())); let mut basket: HashMap<u32, Properties> = HashMap::new(); basket.insert(1, map_apple); basket.insert(0, map_bagel); let res = Storages::to_arr(basket); assert_eq!( res[0].get("B"), Some(&DataType::PtypString("Bagel".to_string())) ); assert_eq!( res[1].get("A"), Some(&DataType::PtypString("Apple".to_string())) ); }
function_block-function_prefix_line
[ { "content": "fn decode_ptypbinary(buff: &Vec<u8>) -> Result<DataType, Error> {\n\n Ok(DataType::PtypBinary(buff.to_vec()))\n\n}\n\n\n", "file_path": "src/parser/decode.rs", "rank": 1, "score": 97399.3281907708 }, { "content": "fn decode_ptypstring(buff: &Vec<u8>) -> Result<DataType, Erro...
Rust
src/librustc_mir/transform/nll/constraint_generation.rs
arshiafaradj/rust
2f47a9eb80bc3474b6e89637269ef1f92cfccb7f
use rustc::hir; use rustc::mir::{Location, Lvalue, Mir, Rvalue}; use rustc::mir::visit::Visitor; use rustc::mir::Lvalue::Projection; use rustc::mir::{LvalueProjection, ProjectionElem}; use rustc::infer::InferCtxt; use rustc::traits::{self, ObligationCause}; use rustc::ty::{self, Ty}; use rustc::ty::fold::TypeFoldable; use rustc::util::common::ErrorReported; use rustc_data_structures::fx::FxHashSet; use syntax::codemap::DUMMY_SP; use super::LivenessResults; use super::ToRegionVid; use super::region_infer::RegionInferenceContext; pub(super) fn generate_constraints<'a, 'gcx, 'tcx>( infcx: &InferCtxt<'a, 'gcx, 'tcx>, regioncx: &mut RegionInferenceContext<'tcx>, mir: &Mir<'tcx>, param_env: ty::ParamEnv<'tcx>, liveness: &LivenessResults, ) { ConstraintGeneration { infcx, regioncx, mir, liveness, param_env, }.add_constraints(); } struct ConstraintGeneration<'cx, 'gcx: 'tcx, 'tcx: 'cx> { infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>, regioncx: &'cx mut RegionInferenceContext<'tcx>, mir: &'cx Mir<'tcx>, liveness: &'cx LivenessResults, param_env: ty::ParamEnv<'tcx>, } impl<'cx, 'gcx, 'tcx> ConstraintGeneration<'cx, 'gcx, 'tcx> { fn add_constraints(&mut self) { self.add_liveness_constraints(); self.add_borrow_constraints(); } fn add_liveness_constraints(&mut self) { debug!("add_liveness_constraints()"); for bb in self.mir.basic_blocks().indices() { debug!("add_liveness_constraints: bb={:?}", bb); self.liveness .regular .simulate_block(self.mir, bb, |location, live_locals| { for live_local in live_locals.iter() { let live_local_ty = self.mir.local_decls[live_local].ty; self.add_regular_live_constraint(live_local_ty, location); } }); self.liveness .drop .simulate_block(self.mir, bb, |location, live_locals| { for live_local in live_locals.iter() { let live_local_ty = self.mir.local_decls[live_local].ty; self.add_drop_live_constraint(live_local_ty, location); } }); } } fn add_regular_live_constraint<T>(&mut self, live_ty: T, location: Location) where T: TypeFoldable<'tcx>, { debug!( "add_regular_live_constraint(live_ty={:?}, location={:?})", live_ty, location ); self.infcx .tcx .for_each_free_region(&live_ty, |live_region| { let vid = live_region.to_region_vid(); self.regioncx.add_live_point(vid, location); }); } fn add_drop_live_constraint(&mut self, dropped_ty: Ty<'tcx>, location: Location) { debug!( "add_drop_live_constraint(dropped_ty={:?}, location={:?})", dropped_ty, location ); let tcx = self.infcx.tcx; let mut types = vec![(dropped_ty, 0)]; let mut known = FxHashSet(); while let Some((ty, depth)) = types.pop() { let span = DUMMY_SP; let result = match tcx.dtorck_constraint_for_ty(span, dropped_ty, depth, ty) { Ok(result) => result, Err(ErrorReported) => { continue; } }; let ty::DtorckConstraint { outlives, dtorck_types, } = result; for outlive in outlives { if let Some(ty) = outlive.as_type() { self.add_regular_live_constraint(ty, location); } else if let Some(r) = outlive.as_region() { self.add_regular_live_constraint(r, location); } else { bug!() } } for ty in dtorck_types { let cause = ObligationCause::dummy(); match traits::fully_normalize(self.infcx, cause, self.param_env, &ty) { Ok(ty) => match ty.sty { ty::TyParam(..) | ty::TyProjection(..) | ty::TyAnon(..) => { self.add_regular_live_constraint(ty, location); } _ => if known.insert(ty) { types.push((ty, depth + 1)); }, }, Err(errors) => { self.infcx.report_fulfillment_errors(&errors, None); } } } } } fn add_borrow_constraints(&mut self) { self.visit_mir(self.mir); } fn add_reborrow_constraint( &mut self, location: Location, borrow_region: ty::Region<'tcx>, borrowed_lv: &Lvalue<'tcx>, ) { if let Projection(ref proj) = *borrowed_lv { let LvalueProjection { ref base, ref elem } = **proj; if let ProjectionElem::Deref = *elem { let tcx = self.infcx.tcx; let base_ty = base.ty(self.mir, tcx).to_ty(tcx); let base_sty = &base_ty.sty; if let ty::TyRef(base_region, ty::TypeAndMut{ ty: _, mutbl }) = *base_sty { match mutbl { hir::Mutability::MutImmutable => { }, hir::Mutability::MutMutable => { self.add_reborrow_constraint(location, borrow_region, base); }, } let span = self.mir.source_info(location).span; self.regioncx.add_outlives(span, base_region.to_region_vid(), borrow_region.to_region_vid(), location.successor_within_block()); } } } } } impl<'cx, 'gcx, 'tcx> Visitor<'tcx> for ConstraintGeneration<'cx, 'gcx, 'tcx> { fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) { debug!("visit_rvalue(rvalue={:?}, location={:?})", rvalue, location); if let Rvalue::Ref(region, _bk, ref borrowed_lv) = *rvalue { self.add_reborrow_constraint(location, region, borrowed_lv); } self.super_rvalue(rvalue, location); } }
use rustc::hir; use rustc::mir::{Location, Lvalue, Mir, Rvalue}; use rustc::mir::visit::Visitor; use rustc::mir::Lvalue::Projection; use rustc::mir::{LvalueProjection, ProjectionElem}; use rustc::infer::InferCtxt; use rustc::traits::{self, ObligationCause}; use rustc::ty::{self, Ty}; use rustc::ty::fold::TypeFoldable; use rustc::util::common::ErrorReported; use rustc_data_structures::fx::FxHashSet; use syntax::codemap::DUMMY_SP; use super::LivenessResults; use super::ToRegionVid; use super::region_infer::RegionInferenceContext; pub(super) fn generate_constraints<'a, 'gcx, 'tcx>( infcx: &InferCtxt<'a, 'gcx, 'tcx>, regioncx: &mut RegionInferenceContext<'tcx>, mir: &Mir<'tcx>, param_env: ty::ParamEnv<'tcx>, liveness: &LivenessResults, ) { ConstraintGeneration { infcx, regioncx, mir, liveness, param_env, }.add_constraints(); } struct ConstraintGeneration<'cx, 'gcx: 'tcx, 'tcx: 'cx> { infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>, regioncx: &'cx mut RegionInferenceContext<'tcx>, mir: &'cx Mir<'tcx>, liveness: &'cx LivenessResults, param_env: ty::ParamEnv<'tcx>, } impl<'cx, 'gcx, 'tcx> ConstraintGeneration<'cx, 'gcx, 'tcx> { fn add_constraints(&mut self) { self.add_liveness_constraints(); self.add_borrow_constraints(); } fn add_liveness_constraints(&mut self) { debug!("add_liveness_constraints()"); for bb in self.mir.basic_blocks().indices() { debug!("add_liveness_constraints: bb={:?}", bb); self.liveness .regular .simulate_block(self.mir, bb, |location, live_locals| { for live_local in live_locals.iter() { let live_local_ty = self.mir.local_decls[live_local].ty; self.add_regular_live_constraint(live_local_ty, location); } }); self.liveness .drop .simulate_block(self.mir, bb, |location, live_locals| { for live_local in live_locals.iter() { let live_local_ty = self.mir.local_decls[live_local].ty; self.add_drop_live_constraint(live_local_ty, location); } }); } } fn add_regular_live_constraint<T>(&mut self, live_ty: T, location: Location) where T: TypeFoldable<'tcx>, { debug!( "add_regular_live_constraint(live_ty={:?}, location={:?})", live_ty, location ); self.infcx .tcx .for_each_free_region(&live_ty, |live_region| { let vid = live_region.to_region_vid(); self.regioncx.add_live_point(vid, location); }); } fn add_drop_live_constraint(&mut self, dropped_ty: Ty<'tcx>, location: Location) { debug!( "add_drop_live_constraint(dropped_ty={:?}, location={:?})", dropped_ty, location ); let tcx = self.infcx.tcx; let mut types = vec![(dropped_ty, 0)]; let mut known = FxHashSet(); while let Some((ty, depth)) = types.pop() { let span = DUMMY_SP; let result = match tcx.dtorck_constraint_for_ty(span, dropped_ty, depth, ty) { Ok(result) => result, Err(ErrorReported) => { continue; } }; let ty::DtorckConstraint { outlives, dtorck_types, } = result; for outlive in outlives { if let Some(ty) = outlive.as_type() { self.add_regular_live_constraint(ty, location); } else if let Some(r) = outlive.as_region() { self.add_regular_live_constraint(r, location); } else { bug!() } } for ty in dtorck_types { let cause = ObligationCause::dummy(); match traits::fully_normalize(self.infcx, cause, self.param_env, &ty) { Ok(ty) => match ty.sty { ty::TyParam(..) | ty::TyProjection(..) | ty::TyAnon(..) => { self.add_regular_live_constraint(ty, location); } _ => if known.insert(ty) { types.push((ty, depth + 1)); }, }, Err(errors) => { self.infcx.report_fulfillment_errors(&errors, None); } } } } } fn add_borrow_constraints(&mut self) { self.visit_mir(self.mir); } fn add_reborrow_constraint( &mut self, location: Location, borrow_region: ty::Region<'tcx>, borrowed_lv: &Lvalue<'tcx>, ) { if let Projection(ref proj) = *borrowed_lv {
} impl<'cx, 'gcx, 'tcx> Visitor<'tcx> for ConstraintGeneration<'cx, 'gcx, 'tcx> { fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) { debug!("visit_rvalue(rvalue={:?}, location={:?})", rvalue, location); if let Rvalue::Ref(region, _bk, ref borrowed_lv) = *rvalue { self.add_reborrow_constraint(location, region, borrowed_lv); } self.super_rvalue(rvalue, location); } }
let LvalueProjection { ref base, ref elem } = **proj; if let ProjectionElem::Deref = *elem { let tcx = self.infcx.tcx; let base_ty = base.ty(self.mir, tcx).to_ty(tcx); let base_sty = &base_ty.sty; if let ty::TyRef(base_region, ty::TypeAndMut{ ty: _, mutbl }) = *base_sty { match mutbl { hir::Mutability::MutImmutable => { }, hir::Mutability::MutMutable => { self.add_reborrow_constraint(location, borrow_region, base); }, } let span = self.mir.source_info(location).span; self.regioncx.add_outlives(span, base_region.to_region_vid(), borrow_region.to_region_vid(), location.successor_within_block()); } } } }
function_block-function_prefixed
[]
Rust
src/xlnet/attention.rs
sftse/rust-bert
5c1c2aa19971a613323fee423c035e0d39d27465
use crate::common::dropout::Dropout; use crate::xlnet::XLNetConfig; use std::borrow::Borrow; use tch::nn::Init; use tch::{nn, Kind, Tensor}; #[derive(Debug)] pub struct LayerState { pub prev_content: Tensor, } impl Clone for LayerState { fn clone(&self) -> Self { LayerState { prev_content: self.prev_content.copy(), } } } impl LayerState { pub(crate) fn reorder_cache(&mut self, new_indices: &Tensor) { self.prev_content = self.prev_content.index_select(1, new_indices); } } #[derive(Debug)] pub struct XLNetRelativeAttention { num_attention_heads: i64, attention_head_size: i64, hidden_size: i64, dropout: Dropout, output_attentions: bool, query: Tensor, key: Tensor, value: Tensor, output: Tensor, pos: Tensor, r_r_bias: Tensor, r_s_bias: Tensor, r_w_bias: Tensor, seg_embed: Tensor, layer_norm: nn::LayerNorm, scale: f64, } impl XLNetRelativeAttention { pub fn new<'p, P>(p: P, config: &XLNetConfig) -> XLNetRelativeAttention where P: Borrow<nn::Path<'p>>, { assert_eq!( config.d_model % config.d_head, 0, "Hidden size not a multiple of attention heads dimension" ); let p = p.borrow(); let query = p.var( "q", &[config.d_model, config.n_head, config.d_head], Init::KaimingUniform, ); let key = p.var( "k", &[config.d_model, config.n_head, config.d_head], Init::KaimingUniform, ); let value = p.var( "v", &[config.d_model, config.n_head, config.d_head], Init::KaimingUniform, ); let output = p.var( "o", &[config.d_model, config.n_head, config.d_head], Init::KaimingUniform, ); let pos = p.var( "r", &[config.d_model, config.n_head, config.d_head], Init::KaimingUniform, ); let r_r_bias = p.var( "r_r_bias", &[config.n_head, config.d_head], Init::KaimingUniform, ); let r_s_bias = p.var( "r_s_bias", &[config.n_head, config.d_head], Init::KaimingUniform, ); let r_w_bias = p.var( "r_w_bias", &[config.n_head, config.d_head], Init::KaimingUniform, ); let seg_embed = p.var( "seg_embed", &[2, config.n_head, config.d_head], Init::KaimingUniform, ); let dropout = Dropout::new(config.dropout); let output_attentions = config.output_attentions.unwrap_or(false); let layer_norm_eps = config.layer_norm_eps.unwrap_or(1e-12); let layer_norm_config = nn::LayerNormConfig { eps: layer_norm_eps, ..Default::default() }; let layer_norm = nn::layer_norm(p / "layer_norm", vec![config.d_model], layer_norm_config); let scale = 1f64 / ((config.d_head as f64).powf(0.5f64)); XLNetRelativeAttention { num_attention_heads: config.n_head, attention_head_size: config.d_head, hidden_size: config.d_model, dropout, output_attentions, query, key, value, output, pos, r_r_bias, r_s_bias, r_w_bias, seg_embed, layer_norm, scale, } } fn rel_shift_bnij(&self, x: &Tensor, klen: i64) -> Tensor { let shape = x.size(); x.reshape(&[shape[0], shape[1], shape[3], shape[2]]) .narrow(2, 1, shape[3] - 1) .reshape(&[shape[0], shape[1], shape[2], shape[3] - 1]) .index_select(3, &Tensor::arange(klen, (Kind::Int64, x.device()))) } fn rel_attention_core( &self, q_head: &Tensor, k_head_h: &Tensor, v_head_h: &Tensor, k_head_r: &Tensor, seg_mat: Option<&Tensor>, attention_mask: Option<&Tensor>, train: bool, ) -> (Tensor, Option<Tensor>) { let ac = Tensor::einsum("ibnd,jbnd->bnij", &[&(q_head + &self.r_w_bias), k_head_h]); let bd = self.rel_shift_bnij( &Tensor::einsum("ibnd,jbnd->bnij", &[&(q_head + &self.r_r_bias), k_head_r]), ac.size()[3], ); let ef = match seg_mat { Some(seg_mat) => { let ef = Tensor::einsum( "ibnd,snd->ibns", &[&(q_head + &self.r_s_bias), &self.seg_embed], ); Tensor::einsum("ijbs,ibns->bnij", &[seg_mat, &ef]) } None => Tensor::zeros(&[1], (Kind::Float, ac.device())), }; let mut attention_score = (ac + bd + ef) * self.scale; if let Some(value) = attention_mask { attention_score = attention_score - value.permute(&[2, 3, 0, 1]) * 1e30; }; let attention_probas = attention_score .softmax(3, Kind::Float) .apply_t(&self.dropout, train); let attention_vector = Tensor::einsum("bnij,jbnd->ibnd", &[&attention_probas, v_head_h]); if self.output_attentions { ( attention_vector, Some(attention_probas.permute(&[2, 3, 0, 1])), ) } else { (attention_vector, None) } } fn post_attention( &self, h: &Tensor, attention_vector: &Tensor, residual: bool, train: bool, ) -> Tensor { let mut attention_out = Tensor::einsum("ibnd,hnd->ibh", &[attention_vector, &self.output]) .apply_t(&self.dropout, train); if residual { attention_out = attention_out + h; }; attention_out.apply(&self.layer_norm) } pub fn forward_t( &self, h: &Tensor, g: Option<&Tensor>, attn_mask_h: Option<&Tensor>, attn_mask_g: Option<&Tensor>, r: &Tensor, seg_mat: Option<&Tensor>, layer_state: Option<LayerState>, target_mapping: Option<&Tensor>, train: bool, ) -> (Tensor, Option<Tensor>, Option<Tensor>, Option<Tensor>) { let cat_value = if let Some(mems) = &layer_state { if mems.prev_content.size().len() > 1 { Some(Tensor::cat(&[&mems.prev_content, h], 0)) } else { None } } else { None }; let cat = match &cat_value { Some(value) => value, None => h, }; let q_head_h = Tensor::einsum("ibh,hnd->ibnd", &[h, &self.query]); let k_head_h = Tensor::einsum("ibh,hnd->ibnd", &[cat, &self.key]); let v_head_h = Tensor::einsum("ibh,hnd->ibnd", &[cat, &self.value]); let k_head_r = Tensor::einsum("ibh,hnd->ibnd", &[r, &self.pos]); let (attention_vec_h, attention_probas_h) = self.rel_attention_core( &q_head_h, &k_head_h, &v_head_h, &k_head_r, seg_mat, attn_mask_h, train, ); let output_h = self.post_attention(h, &attention_vec_h, true, train); let (output_g, attention_probas_g) = if let Some(g) = g { let q_head_g = Tensor::einsum("ibh,hnd->ibnd", &[g, &self.query]); let (attention_vec_g, attention_probas_g) = match target_mapping { Some(target_mapping) => { let q_head_g = Tensor::einsum("mbnd,mlb->lbnd", &[&q_head_g, target_mapping]); let (attention_vec_g, attention_probas_g) = self.rel_attention_core( &q_head_g, &k_head_h, &v_head_h, &k_head_r, seg_mat, attn_mask_g, train, ); let attention_vec_g = Tensor::einsum("lbnd,mlb->mbnd", &[&attention_vec_g, target_mapping]); (attention_vec_g, attention_probas_g) } None => self.rel_attention_core( &q_head_g, &k_head_h, &v_head_h, &k_head_r, seg_mat, attn_mask_g, train, ), }; let output_g = self.post_attention(g, &attention_vec_g, true, train); (Some(output_g), attention_probas_g) } else { (None, None) }; (output_h, output_g, attention_probas_h, attention_probas_g) } }
use crate::common::dropout::Dropout; use crate::xlnet::XLNetConfig; use std::borrow::Borrow; use tch::nn::Init; use tch::{nn, Kind, Tensor}; #[derive(Debug)] pub struct LayerState { pub prev_content: Tensor, } impl Clone for LayerState { fn clone(&self) -> Self { LayerState { prev_content: self.prev_content.copy(), } } } impl LayerState { pub(crate) fn reorder_cache(&mut self, new_indices: &Tensor) { self.prev_content = self.prev_content.index_select(1, new_indices); } } #[derive(Debug)] pub struct XLNetRelativeAttention { num_attention_heads: i64, attention_head_size: i64, hidden_size: i64, dropout: Dropout, output_attentions: bool, query: Tensor, key: Tensor, value: Tensor, output: Tensor, pos: Tensor, r_r_bias: Tensor, r_s_bias: Tensor, r_w_bias: Tensor, seg_embed: Tensor, layer_norm: nn::LayerNorm, scale: f64, } impl XLNetRelativeAttention { pub fn new<'p, P>(p: P, config: &XLNetConfig) -> XLNetRelativeAttention where P: Borrow<nn::Path<'p>>, { assert_eq!( config.d_model % config.d_head, 0, "Hidden size not a multiple of attention heads dimension" ); let p = p.borrow(); let query = p.var( "q", &[config.d_model, config.n_head, config.d_head], Init::KaimingUniform, ); let key = p.var( "k", &[config.d_model, config.n_head, config.d_head], Init::KaimingUniform, ); let value = p.var( "v", &[config.d_model, config.n_head, config.d_head], Init::KaimingUniform, ); let output = p.var( "o", &[config.d_model, config.n_head, config.d_head], Init::KaimingUniform, ); let pos = p.var( "r", &[config.d_model, config.n_head, config.d_head], Init::KaimingUniform, ); let r_r_bias = p.var( "r_r_bias", &[config.n_head, config.d_head], Init::KaimingUniform, ); let r_s_bias = p.var( "r_s_bias", &[config.n_head, config.d_head], Init::KaimingUniform, ); let r_w_bias = p.var( "r_w_bias", &[config.n_head, config.d_head], Init::KaimingUniform, ); let seg_embed = p.var( "seg_embed", &[2, config.n_head, config.d_head], Init::KaimingUniform, ); let dropout = Dropout::new(config.dropout); let output_attentions = config.output_attentions.unwrap_or(false); let layer_norm_eps = config.layer_norm_eps.unwrap_or(1e-12); let layer_norm_config = nn::LayerNormConfig { eps: layer_norm_eps, ..Default::default() }; let layer_norm = nn::layer_norm(p / "layer_norm", vec![config.d_model], layer_norm_config); let scale = 1f64 / ((config.d_head as f64).powf(0.5f64)); XLNetRelativeAttention { num_attention_heads: config.n_head, attention_head_size: config.d_head, hidden_size: config.d_model, dropout, output_attentions, query, key, value, output, pos, r_r_bias, r_s_bias, r_w_bias, seg_embed, layer_norm, scale, } } fn rel_shift_bnij(&self, x: &Tensor, klen: i64) -> Tensor { let shape = x.size(); x.reshape(&[shape[0], shape[1], shape[3], shape[2]]) .narrow(2, 1, shape[3] - 1) .reshape(&[shape[0], shape[1], shape[2], shape[3] - 1]) .index_select(3, &Tensor::arange(klen, (Kind::Int64, x.device()))) } fn rel_attention_core( &self, q_head: &Tensor, k_head_h: &Tensor, v_head_h: &Tensor, k_head_r: &Tensor, seg_mat: Option<&Tensor>, attention_mask: Option<&Tensor>, train: bool, ) -> (Tensor, Option<Tensor>) { let ac = Tensor::einsum("ibnd,jbnd->bnij", &[&(q_head + &self.r_w_bias), k_head_h]); let bd = self.rel_shift_bnij( &Tensor::einsum("ibnd,jbnd->bnij", &[&(q_head + &self.r_r_bias), k_head_r]), ac.size()[3], ); let ef = match seg_mat { Some(seg_mat) => { let ef = Tensor::einsum( "ibnd,snd->ibns", &[&(q_head + &self.r_s_bias), &self.seg_embed], ); Tensor::einsum("ijbs,ibns->bnij", &[seg_mat, &ef]) } None => Tensor::zeros(&[1], (Kind::Float, ac.device())), }; let mut attention_score = (ac + bd + ef) * self.scale; if let Some(value) = attention_mask { attention_score = attention_score - value.permute(&[2, 3, 0, 1]) * 1e30; }; let attention_probas = attention_score .softmax(3, Kind::Float) .apply_t(&self.dropout, train); let attention_vector = Tensor::einsum("bnij,jbnd->ibnd", &[&attention_probas, v_head_h]); if self.output_attentions { ( attention_vector, Some(attention_probas.permute(&[2, 3, 0, 1])), ) } else { (attention_vector, None) } }
pub fn forward_t( &self, h: &Tensor, g: Option<&Tensor>, attn_mask_h: Option<&Tensor>, attn_mask_g: Option<&Tensor>, r: &Tensor, seg_mat: Option<&Tensor>, layer_state: Option<LayerState>, target_mapping: Option<&Tensor>, train: bool, ) -> (Tensor, Option<Tensor>, Option<Tensor>, Option<Tensor>) { let cat_value = if let Some(mems) = &layer_state { if mems.prev_content.size().len() > 1 { Some(Tensor::cat(&[&mems.prev_content, h], 0)) } else { None } } else { None }; let cat = match &cat_value { Some(value) => value, None => h, }; let q_head_h = Tensor::einsum("ibh,hnd->ibnd", &[h, &self.query]); let k_head_h = Tensor::einsum("ibh,hnd->ibnd", &[cat, &self.key]); let v_head_h = Tensor::einsum("ibh,hnd->ibnd", &[cat, &self.value]); let k_head_r = Tensor::einsum("ibh,hnd->ibnd", &[r, &self.pos]); let (attention_vec_h, attention_probas_h) = self.rel_attention_core( &q_head_h, &k_head_h, &v_head_h, &k_head_r, seg_mat, attn_mask_h, train, ); let output_h = self.post_attention(h, &attention_vec_h, true, train); let (output_g, attention_probas_g) = if let Some(g) = g { let q_head_g = Tensor::einsum("ibh,hnd->ibnd", &[g, &self.query]); let (attention_vec_g, attention_probas_g) = match target_mapping { Some(target_mapping) => { let q_head_g = Tensor::einsum("mbnd,mlb->lbnd", &[&q_head_g, target_mapping]); let (attention_vec_g, attention_probas_g) = self.rel_attention_core( &q_head_g, &k_head_h, &v_head_h, &k_head_r, seg_mat, attn_mask_g, train, ); let attention_vec_g = Tensor::einsum("lbnd,mlb->mbnd", &[&attention_vec_g, target_mapping]); (attention_vec_g, attention_probas_g) } None => self.rel_attention_core( &q_head_g, &k_head_h, &v_head_h, &k_head_r, seg_mat, attn_mask_g, train, ), }; let output_g = self.post_attention(g, &attention_vec_g, true, train); (Some(output_g), attention_probas_g) } else { (None, None) }; (output_h, output_g, attention_probas_h, attention_probas_g) } }
fn post_attention( &self, h: &Tensor, attention_vector: &Tensor, residual: bool, train: bool, ) -> Tensor { let mut attention_out = Tensor::einsum("ibnd,hnd->ibh", &[attention_vector, &self.output]) .apply_t(&self.dropout, train); if residual { attention_out = attention_out + h; }; attention_out.apply(&self.layer_norm) }
function_block-full_function
[ { "content": "pub fn stable_argsort(input_tensor: &Tensor, dim: i64) -> Tensor {\n\n let scaling_dim = input_tensor.size()[dim as usize];\n\n let scaled_offset = Tensor::arange(scaling_dim, (Kind::Int, input_tensor.device()))\n\n .view([1, 1, -1])\n\n .expand(&input_tensor.size(), true);\n\n...
Rust
src/kernel.rs
Mic92/vmsh
296a09102abece5df0135afb9678261d5a7b6c20
use log::{debug, info}; use nix::sys::mman::ProtFlags; use simple_error::{require_with, try_with, SimpleError}; use std::collections::HashMap; use std::ffi::CStr; use std::mem::{self, size_of}; use std::ops::Range; use vm_memory::remote_mem::process_read_bytes; use crate::guest_mem::{GuestMem, MappedMemory}; use crate::kvm::hypervisor::Hypervisor; use crate::result::Result; pub const LINUX_KERNEL_KASLR_RANGE: Range<usize> = 0xFFFFFFFF80000000..0xFFFFFFFFC0000000; fn find_subsequence(haystack: &[u8], needle: &[u8]) -> Option<usize> { haystack .windows(needle.len()) .position(|window| window == needle) } fn not_printable(byte: u8) -> bool { !(0x20 < byte && byte < 0x7E) } fn round_up(num: usize, align: usize) -> usize { ((num + align - 1) / align) * align } fn find_ksymtab_strings_section(mem: &[u8]) -> Option<Range<usize>> { let idx = find_subsequence(mem, b"init_task")?; let start_offset = mem[..idx] .windows(2) .rev() .position(|b| not_printable(b[0]) && not_printable(b[1]))?; let start = round_up(idx - start_offset, 4); let end_offset = mem[idx..] .windows(2) .position(|b| not_printable(b[0]) && not_printable(b[1]))?; let end = idx + end_offset + 1; Some(start..end) } #[repr(C)] #[derive(Debug)] pub struct kernel_symbol { pub value_offset: libc::c_int, pub name_offset: libc::c_int, pub namespace_offset: libc::c_int, } #[repr(C)] #[derive(Debug)] pub struct kernel_symbol_5_3 { pub value_offset: libc::c_int, pub name_offset: libc::c_int, } #[repr(C)] #[derive(Debug)] pub struct kernel_symbol_4_18 { pub value: libc::c_ulong, pub name: libc::c_ulong, } unsafe fn cast_kernel_sym(mem: &[u8]) -> &kernel_symbol { &*mem::transmute::<_, *const kernel_symbol>(mem.as_ptr()) } fn check_single_kernel_sym( mem: &[u8], ii: usize, sym_size: usize, strings_range: &Range<usize>, ) -> Option<usize> { let start = ii - sym_size; let sym = unsafe { cast_kernel_sym(&mem[start..ii]) }; let field_offset = &sym.name_offset as *const i32 as usize - sym as *const kernel_symbol as usize; let sum = start .checked_add(sym.name_offset as usize) .and_then(|s| s.checked_add(field_offset)); if let Some(name_idx) = sum { if strings_range.contains(&name_idx) { return Some(name_idx); } } None } fn check_kernel_sym( mem: &[u8], strings_range: &Range<usize>, sym_size: usize, ii: usize, ) -> Option<usize> { if 2 * sym_size > ii { return None; } if let Some(addr1) = check_single_kernel_sym(mem, ii, sym_size, strings_range) { if let Some(addr2) = check_single_kernel_sym(mem, ii - sym_size, sym_size, strings_range) { if addr1 != addr2 { return Some(sym_size); } } } None } fn get_kernel_symbol_legacy(mem: &[u8]) -> &kernel_symbol_4_18 { unsafe { &*(mem.as_ptr() as *const kernel_symbol_4_18) } } fn check_kernel_sym_legacy( mem: &[u8], mem_base: usize, strings_range: &Range<usize>, ii: usize, ) -> Option<usize> { let sym_size = size_of::<kernel_symbol_4_18>(); if sym_size > ii { return None; } let sym = get_kernel_symbol_legacy(&mem[ii - sym_size..ii]); let virt_range = strings_range.start + mem_base..strings_range.end + mem_base; if virt_range.contains(&(sym.name as usize)) { let sym2 = get_kernel_symbol_legacy(&mem[ii - 2 * sym_size..ii - sym_size]); if virt_range.contains(&(sym2.name as usize)) { return Some(sym_size); } } None } fn get_ksymtab_start( mem: &[u8], mem_base: usize, strings_range: &Range<usize>, ) -> Option<(usize, usize)> { let step_size = size_of::<u32>(); for ii in (0..strings_range.start + 1).rev().step_by(step_size) { let sym_size = check_kernel_sym(mem, strings_range, size_of::<kernel_symbol>(), ii) .or_else(|| check_kernel_sym(mem, strings_range, size_of::<kernel_symbol_5_3>(), ii)) .or_else(|| check_kernel_sym_legacy(mem, mem_base, strings_range, ii)); if let Some(sym_size) = sym_size { return Some((ii, sym_size)); } } None } fn apply_offset(addr: usize, offset: libc::c_int) -> usize { if offset < 0 { addr - (-offset as usize) } else { addr - offset as usize } } fn symbol_name(mem: &[u8], idx: usize) -> Result<String> { let len = require_with!( mem[idx..].iter().position(|c| *c == 0), "symbol name does not end" ); let name = try_with!( CStr::from_bytes_with_nul(&mem[idx..idx + len + 1]), "invalid symbol name" ); Ok(try_with!(name.to_str(), "invalid encoding for symbol name").to_owned()) } fn get_kernel_symbols( mem: &[u8], mem_base: usize, ksymtab_strings: Range<usize>, ) -> Result<HashMap<String, usize>> { let mut syms = HashMap::new(); let (start, sym_size) = require_with!( get_ksymtab_start(mem, mem_base, &ksymtab_strings), "no ksymtab found" ); info!( "found ksymtab {} bytes before ksymtab_strings at 0x{:x}", ksymtab_strings.start - start, start + mem_base ); let mut sym_count = 0; if sym_size == size_of::<kernel_symbol_4_18>() { let virt_range = ksymtab_strings.start + mem_base..ksymtab_strings.end + mem_base; for ii in (0..start + 1).rev().step_by(sym_size) { let sym = get_kernel_symbol_legacy(&mem[ii - sym_size..ii]); if !virt_range.contains(&(sym.name as usize)) { break; } let name = symbol_name(mem, sym.name as usize - mem_base)?; sym_count += 1; debug!("{} @ {:x}", name, sym.value); syms.insert(name, sym.value as usize); } } else { for ii in (0..start + 1).rev().step_by(sym_size) { let sym_start = ii - sym_size; let sym = unsafe { cast_kernel_sym(&mem[sym_start..ii]) }; let name_offset = &sym.name_offset as *const i32 as usize - sym as *const kernel_symbol as usize; let value_offset = &sym.value_offset as *const i32 as usize - sym as *const kernel_symbol as usize; let name_idx = match sym_start .checked_add(name_offset) .and_then(|s| s.checked_add(sym.name_offset as usize)) { Some(idx) => idx, None => break, }; if !ksymtab_strings.contains(&name_idx) { break; } let value_ptr = apply_offset(mem_base + sym_start + value_offset, sym.value_offset); let name = symbol_name(mem, name_idx)?; sym_count += 1; debug!("{} @ {:x}", name, value_ptr); syms.insert(name, value_ptr); } } info!("found {} kernel symbols", sym_count); Ok(syms) } pub struct Kernel { pub range: Range<usize>, pub memory_sections: Vec<MappedMemory>, pub symbols: HashMap<String, usize>, pub largest_gap: Range<usize>, } impl Kernel { pub fn space_before(&self) -> usize { self.range.start - LINUX_KERNEL_KASLR_RANGE.start } pub fn space_after(&self) -> usize { LINUX_KERNEL_KASLR_RANGE.end - self.range.end } } pub fn find_kernel(guest_mem: &GuestMem, hv: &Hypervisor) -> Result<Kernel> { let (memory_sections, largest_gap) = try_with!( guest_mem.find_kernel_sections(hv, LINUX_KERNEL_KASLR_RANGE), "could not find Linux kernel in VM memory" ); let kernel_last = require_with!(memory_sections.last(), "no sections found"); let kernel_start = require_with!(memory_sections.first(), "no sections found").virt_start; let kernel_end = kernel_last.virt_start + kernel_last.len; info!( "found linux kernel at {:#x}-{:#x}", kernel_start, kernel_end ); let symbols = memory_sections.iter().find_map(|s| { if s.prot != ProtFlags::PROT_READ { return None; } let mut mem = vec![0; s.len]; let mem_base = s.phys_start.host_addr() as *const libc::c_void; if let Err(e) = process_read_bytes(hv.pid, &mut mem, mem_base) { return Some(Err(SimpleError::new(format!( "failed to read linux kernel from hypervisor memory: {}", e )))); } let strings_range = find_ksymtab_strings_section(&mem)?; let from_addr = s.phys_start.add(strings_range.start); let to_addr = s.phys_start.add(strings_range.end - 1); let string_num = mem[strings_range.clone()] .iter() .filter(|c| **c == 0) .count(); info!( "found ksymtab_string at physical {:#x}:{:#x} with {} strings", from_addr.value, to_addr.value, string_num ); match get_kernel_symbols(&mem, s.virt_start, strings_range) { Err(e) => Some(Err(SimpleError::new(format!( "failed to parse kernel symbols: {}", e )))), Ok(syms) => Some(Ok(syms)), } }); let symbols = require_with!(symbols, "could not find section with kernel symbols")?; Ok(Kernel { range: kernel_start..kernel_end, memory_sections, symbols, largest_gap, }) }
use log::{debug, info}; use nix::sys::mman::ProtFlags; use simple_error::{require_with, try_with, SimpleError}; use std::collections::HashMap; use std::ffi::CStr; use std::mem::{self, size_of}; use std::ops::Range; use vm_memory::remote_mem::process_read_bytes; use crate::guest_mem::{GuestMem, MappedMemory}; use crate::kvm::hypervisor::Hypervisor; use crate::result::Result; pub const LINUX_KERNEL_KASLR_RANGE: Range<usize> = 0xFFFFFFFF80000000..0xFFFFFFFFC0000000; fn find_subsequence(haystack: &[u8], needle: &[u8]) -> Option<usize> { haystack .windows(needle.len()) .position(|window| window == needle) } fn not_printable(byte: u8) -> bool { !(0x20 < byte && byte < 0x7E) } fn round_up(num: usize, align: usize) -> usize { ((num + align - 1) / align) * align } fn find_ksymtab_strings_section(mem: &[u8]) -> Optio
end = idx + end_offset + 1; Some(start..end) } #[repr(C)] #[derive(Debug)] pub struct kernel_symbol { pub value_offset: libc::c_int, pub name_offset: libc::c_int, pub namespace_offset: libc::c_int, } #[repr(C)] #[derive(Debug)] pub struct kernel_symbol_5_3 { pub value_offset: libc::c_int, pub name_offset: libc::c_int, } #[repr(C)] #[derive(Debug)] pub struct kernel_symbol_4_18 { pub value: libc::c_ulong, pub name: libc::c_ulong, } unsafe fn cast_kernel_sym(mem: &[u8]) -> &kernel_symbol { &*mem::transmute::<_, *const kernel_symbol>(mem.as_ptr()) } fn check_single_kernel_sym( mem: &[u8], ii: usize, sym_size: usize, strings_range: &Range<usize>, ) -> Option<usize> { let start = ii - sym_size; let sym = unsafe { cast_kernel_sym(&mem[start..ii]) }; let field_offset = &sym.name_offset as *const i32 as usize - sym as *const kernel_symbol as usize; let sum = start .checked_add(sym.name_offset as usize) .and_then(|s| s.checked_add(field_offset)); if let Some(name_idx) = sum { if strings_range.contains(&name_idx) { return Some(name_idx); } } None } fn check_kernel_sym( mem: &[u8], strings_range: &Range<usize>, sym_size: usize, ii: usize, ) -> Option<usize> { if 2 * sym_size > ii { return None; } if let Some(addr1) = check_single_kernel_sym(mem, ii, sym_size, strings_range) { if let Some(addr2) = check_single_kernel_sym(mem, ii - sym_size, sym_size, strings_range) { if addr1 != addr2 { return Some(sym_size); } } } None } fn get_kernel_symbol_legacy(mem: &[u8]) -> &kernel_symbol_4_18 { unsafe { &*(mem.as_ptr() as *const kernel_symbol_4_18) } } fn check_kernel_sym_legacy( mem: &[u8], mem_base: usize, strings_range: &Range<usize>, ii: usize, ) -> Option<usize> { let sym_size = size_of::<kernel_symbol_4_18>(); if sym_size > ii { return None; } let sym = get_kernel_symbol_legacy(&mem[ii - sym_size..ii]); let virt_range = strings_range.start + mem_base..strings_range.end + mem_base; if virt_range.contains(&(sym.name as usize)) { let sym2 = get_kernel_symbol_legacy(&mem[ii - 2 * sym_size..ii - sym_size]); if virt_range.contains(&(sym2.name as usize)) { return Some(sym_size); } } None } fn get_ksymtab_start( mem: &[u8], mem_base: usize, strings_range: &Range<usize>, ) -> Option<(usize, usize)> { let step_size = size_of::<u32>(); for ii in (0..strings_range.start + 1).rev().step_by(step_size) { let sym_size = check_kernel_sym(mem, strings_range, size_of::<kernel_symbol>(), ii) .or_else(|| check_kernel_sym(mem, strings_range, size_of::<kernel_symbol_5_3>(), ii)) .or_else(|| check_kernel_sym_legacy(mem, mem_base, strings_range, ii)); if let Some(sym_size) = sym_size { return Some((ii, sym_size)); } } None } fn apply_offset(addr: usize, offset: libc::c_int) -> usize { if offset < 0 { addr - (-offset as usize) } else { addr - offset as usize } } fn symbol_name(mem: &[u8], idx: usize) -> Result<String> { let len = require_with!( mem[idx..].iter().position(|c| *c == 0), "symbol name does not end" ); let name = try_with!( CStr::from_bytes_with_nul(&mem[idx..idx + len + 1]), "invalid symbol name" ); Ok(try_with!(name.to_str(), "invalid encoding for symbol name").to_owned()) } fn get_kernel_symbols( mem: &[u8], mem_base: usize, ksymtab_strings: Range<usize>, ) -> Result<HashMap<String, usize>> { let mut syms = HashMap::new(); let (start, sym_size) = require_with!( get_ksymtab_start(mem, mem_base, &ksymtab_strings), "no ksymtab found" ); info!( "found ksymtab {} bytes before ksymtab_strings at 0x{:x}", ksymtab_strings.start - start, start + mem_base ); let mut sym_count = 0; if sym_size == size_of::<kernel_symbol_4_18>() { let virt_range = ksymtab_strings.start + mem_base..ksymtab_strings.end + mem_base; for ii in (0..start + 1).rev().step_by(sym_size) { let sym = get_kernel_symbol_legacy(&mem[ii - sym_size..ii]); if !virt_range.contains(&(sym.name as usize)) { break; } let name = symbol_name(mem, sym.name as usize - mem_base)?; sym_count += 1; debug!("{} @ {:x}", name, sym.value); syms.insert(name, sym.value as usize); } } else { for ii in (0..start + 1).rev().step_by(sym_size) { let sym_start = ii - sym_size; let sym = unsafe { cast_kernel_sym(&mem[sym_start..ii]) }; let name_offset = &sym.name_offset as *const i32 as usize - sym as *const kernel_symbol as usize; let value_offset = &sym.value_offset as *const i32 as usize - sym as *const kernel_symbol as usize; let name_idx = match sym_start .checked_add(name_offset) .and_then(|s| s.checked_add(sym.name_offset as usize)) { Some(idx) => idx, None => break, }; if !ksymtab_strings.contains(&name_idx) { break; } let value_ptr = apply_offset(mem_base + sym_start + value_offset, sym.value_offset); let name = symbol_name(mem, name_idx)?; sym_count += 1; debug!("{} @ {:x}", name, value_ptr); syms.insert(name, value_ptr); } } info!("found {} kernel symbols", sym_count); Ok(syms) } pub struct Kernel { pub range: Range<usize>, pub memory_sections: Vec<MappedMemory>, pub symbols: HashMap<String, usize>, pub largest_gap: Range<usize>, } impl Kernel { pub fn space_before(&self) -> usize { self.range.start - LINUX_KERNEL_KASLR_RANGE.start } pub fn space_after(&self) -> usize { LINUX_KERNEL_KASLR_RANGE.end - self.range.end } } pub fn find_kernel(guest_mem: &GuestMem, hv: &Hypervisor) -> Result<Kernel> { let (memory_sections, largest_gap) = try_with!( guest_mem.find_kernel_sections(hv, LINUX_KERNEL_KASLR_RANGE), "could not find Linux kernel in VM memory" ); let kernel_last = require_with!(memory_sections.last(), "no sections found"); let kernel_start = require_with!(memory_sections.first(), "no sections found").virt_start; let kernel_end = kernel_last.virt_start + kernel_last.len; info!( "found linux kernel at {:#x}-{:#x}", kernel_start, kernel_end ); let symbols = memory_sections.iter().find_map(|s| { if s.prot != ProtFlags::PROT_READ { return None; } let mut mem = vec![0; s.len]; let mem_base = s.phys_start.host_addr() as *const libc::c_void; if let Err(e) = process_read_bytes(hv.pid, &mut mem, mem_base) { return Some(Err(SimpleError::new(format!( "failed to read linux kernel from hypervisor memory: {}", e )))); } let strings_range = find_ksymtab_strings_section(&mem)?; let from_addr = s.phys_start.add(strings_range.start); let to_addr = s.phys_start.add(strings_range.end - 1); let string_num = mem[strings_range.clone()] .iter() .filter(|c| **c == 0) .count(); info!( "found ksymtab_string at physical {:#x}:{:#x} with {} strings", from_addr.value, to_addr.value, string_num ); match get_kernel_symbols(&mem, s.virt_start, strings_range) { Err(e) => Some(Err(SimpleError::new(format!( "failed to parse kernel symbols: {}", e )))), Ok(syms) => Some(Ok(syms)), } }); let symbols = require_with!(symbols, "could not find section with kernel symbols")?; Ok(Kernel { range: kernel_start..kernel_end, memory_sections, symbols, largest_gap, }) }
n<Range<usize>> { let idx = find_subsequence(mem, b"init_task")?; let start_offset = mem[..idx] .windows(2) .rev() .position(|b| not_printable(b[0]) && not_printable(b[1]))?; let start = round_up(idx - start_offset, 4); let end_offset = mem[idx..] .windows(2) .position(|b| not_printable(b[0]) && not_printable(b[1]))?; let
function_block-random_span
[ { "content": "pub fn is_page_aligned(v: usize) -> bool {\n\n v & (page_size() - 1) == 0\n\n}\n\n\n", "file_path": "src/page_math.rs", "rank": 2, "score": 253724.61583958115 }, { "content": "pub fn use_ioregionfd() -> bool {\n\n USE_IOREGIONFD.load(Ordering::Relaxed)\n\n}\n\n\n\npub typ...
Rust
nucleus/src/main.rs
metta-systems/vesper
7d03ea85a2d5ee77b7e8b36e5c9bf1ce41b77084
/* * SPDX-License-Identifier: BlueOak-1.0.0 * Copyright (c) Berkus Decker <berkus+vesper@metta.systems> */ #![no_std] #![no_main] #![feature(decl_macro)] #![feature(allocator_api)] #![feature(ptr_internals)] #![feature(format_args_nl)] #![feature(nonnull_slice_from_raw_parts)] #![feature(custom_test_frameworks)] #![test_runner(crate::tests::test_runner)] #![reexport_test_harness_main = "test_main"] #![deny(missing_docs)] #![deny(warnings)] #![allow(clippy::nonstandard_macro_braces)] #![allow(clippy::upper_case_acronyms)] #![allow(clippy::enum_variant_names)] #[cfg(not(target_arch = "aarch64"))] use architecture_not_supported_sorry; #[macro_use] pub mod arch; pub use arch::*; mod devices; mod macros; mod mm; mod panic; mod platform; #[cfg(feature = "qemu")] mod qemu; mod sync; #[cfg(test)] mod tests; mod write_to; use { crate::platform::rpi3::{ display::{Color, DrawError}, mailbox::{channel, Mailbox, MailboxOps}, vc::VC, }, cfg_if::cfg_if, }; entry!(kmain); static CONSOLE: sync::NullLock<devices::Console> = sync::NullLock::new(devices::Console::new()); static DMA_ALLOCATOR: sync::NullLock<mm::BumpAllocator> = sync::NullLock::new(mm::BumpAllocator::new( memory::map::virt::DMA_HEAP_START as usize, memory::map::virt::DMA_HEAP_END as usize, "Global DMA Allocator", )); fn print_mmu_state_and_features() { memory::mmu::print_features(); } fn init_mmu() { unsafe { memory::mmu::init().unwrap(); } println!("[!] MMU initialised"); print_mmu_state_and_features(); } fn init_exception_traps() { extern "C" { static __exception_vectors_start: u64; } unsafe { let exception_vectors_start: u64 = &__exception_vectors_start as *const _ as u64; arch::traps::set_vbar_el1_checked(exception_vectors_start) .expect("Vector table properly aligned!"); } println!("[!] Exception traps set up"); } #[cfg(not(feature = "noserial"))] fn init_uart_serial() { use crate::platform::rpi3::{gpio::GPIO, mini_uart::MiniUart, pl011_uart::PL011Uart}; let gpio = GPIO::default(); let uart = MiniUart::default(); let uart = uart.prepare(&gpio); CONSOLE.lock(|c| { c.replace_with(uart.into()); }); println!("[0] MiniUART is live!"); let uart = PL011Uart::default(); let mbox = Mailbox::default(); use crate::devices::console::ConsoleOps; CONSOLE.lock(|c| c.flush()); match uart.prepare(mbox, &gpio) { Ok(uart) => { CONSOLE.lock(|c| { c.replace_with(uart.into()); }); println!("[0] UART0 is live!"); } Err(_) => println!("[0] Error switching to PL011 UART, continue with MiniUART"), } } #[inline] pub fn kmain() -> ! { #[cfg(feature = "jtag")] jtag::wait_debugger(); init_mmu(); init_exception_traps(); #[cfg(not(feature = "noserial"))] init_uart_serial(); #[cfg(test)] test_main(); command_prompt(); reboot() } fn command_prompt() { 'cmd_loop: loop { let mut buf = [0u8; 64]; match CONSOLE.lock(|c| c.command_prompt(&mut buf)) { b"mmu" => init_mmu(), b"feats" => print_mmu_state_and_features(), #[cfg(not(feature = "noserial"))] b"uart" => init_uart_serial(), b"disp" => check_display_init(), b"trap" => check_data_abort_trap(), b"map" => arch::memory::print_layout(), b"led on" => set_led(true), b"led off" => set_led(false), b"help" => print_help(), b"end" => break 'cmd_loop, x => println!("[!] Unknown command {:?}, try 'help'", x), } } } fn print_help() { println!("Supported console commands:"); println!(" mmu - initialize MMU"); println!(" feats - print MMU state and supported features"); #[cfg(not(feature = "noserial"))] println!(" uart - try to reinitialize UART serial"); println!(" disp - try to init VC framebuffer and draw some text"); println!(" trap - trigger and recover from a data abort exception"); println!(" map - show kernel memory layout"); println!(" led [on|off] - change RPi LED status"); println!(" end - leave console and reset board"); } fn set_led(enable: bool) { let mut mbox = Mailbox::default(); let index = mbox.request(); let index = mbox.set_led_on(index, enable); let mbox = mbox.end(index); mbox.call(channel::PropertyTagsArmToVc) .map_err(|e| { println!("Mailbox call returned error {}", e); println!("Mailbox contents: {:?}", mbox); }) .ok(); } fn reboot() -> ! { cfg_if! { if #[cfg(feature = "qemu")] { println!("Bye, shutting down QEMU"); qemu::semihosting::exit_success() } else { use crate::platform::rpi3::power::Power; println!("Bye, going to reset now"); Power::new().reset() } } } fn check_display_init() { display_graphics() .map_err(|e| { println!("Error in display: {}", e); }) .ok(); } fn display_graphics() -> Result<(), DrawError> { if let Ok(mut display) = VC::init_fb(800, 600, 32) { println!("Display created"); display.clear(Color::black()); println!("Display cleared"); display.rect(10, 10, 250, 250, Color::rgb(32, 96, 64)); display.draw_text(50, 50, "Hello there!", Color::rgb(128, 192, 255))?; let mut buf = [0u8; 64]; let s = write_to::show(&mut buf, format_args!("Display width {}", display.width)); if s.is_err() { display.draw_text(50, 150, "Error displaying", Color::red())? } else { display.draw_text(50, 150, s.unwrap(), Color::white())? } display.draw_text(150, 50, "RED", Color::red())?; display.draw_text(160, 60, "GREEN", Color::green())?; display.draw_text(170, 70, "BLUE", Color::blue())?; } Ok(()) } fn check_data_abort_trap() { let big_addr: u64 = 3 * 1024 * 1024 * 1024; unsafe { core::ptr::read_volatile(big_addr as *mut u64) }; println!("[i] Whoa! We recovered from an exception."); } #[cfg(test)] mod main_tests { use super::*; #[test_case] fn test_data_abort_trap() { check_data_abort_trap() } }
/* * SPDX-License-Identifier: BlueOak-1.0.0 * Copyright (c) Berkus Decker <berkus+vesper@metta.systems> */ #![no_std] #![no_main] #![feature(decl_macro)] #![feature(allocator_api)] #![feature(ptr_internals)] #![feature(format_args_nl)] #![feature(nonnull_slice_from_raw_parts)] #![feature(custom_test_frameworks)] #![test_runner(crate::tests::test_runner)] #![reexport_test_harness_main = "test_main"] #![deny(missing_docs)] #![deny(warnings)] #![allow(clippy::nonstandard_macro_braces)] #![allow(clippy::upper_case_acronyms)] #![allow(clippy::enum_variant_names)] #[cfg(not(target_arch = "aarch64"))] use architecture_not_supported_sorry; #[macro_use] pub mod arch; pub use arch::*; mod devices; mod macros; mod mm; mod panic; mod platform; #[cfg(feature = "qemu")] mod qemu; mod sync; #[cfg(test)] mod tests; mod write_to; use { crate::platform::rpi3::{ display::{Color, DrawError}, mailbox::{channel, Mailbox, MailboxOps}, vc::VC, }, cfg_if::cfg_if, }; entry!(kmain); static CONSOLE: sync::NullLock<devices::Console> = sync::NullLock::new(devices::Console::new()); static DMA_ALLOCATOR: sync::NullLock<mm::BumpAllocator> = sync::NullLock::new(mm::BumpAllocator::new( memory::map::virt::DMA_HEAP_START as usize, memory::map::virt::DMA_HEAP_END as usize, "Global DMA Allocator", )); fn print_mmu_state_and_features() { memory::mmu::print_features(); } fn init_mmu() { unsafe { memory::mmu::init().unwrap(); } println!("[!] MMU initialised"); print_mmu_state_and_features(); } fn init_exception_traps() { extern "C" { static __exception_vectors_start: u64; } unsafe { let exception_vectors_start: u64 = &__exception_vectors_start as *const _ as u64; arch::traps::set_vbar_el1_checked(exception_vectors_start) .expect("Vector table properly aligned!"); } println!("[!] Exception traps set up"); } #[cfg(not(feature = "noserial"))] fn init_uart_serial() { use crate::platform::rpi3::{gpio::GPIO, mini_uart::MiniUart, pl011_uart::PL011Uart}; let gpio = GPIO::default(); let uart = MiniUart::default(); let uart = uart.prepare(&gpio); CONSOLE.lock(|c| { c.replace_with(uart.into()); }); println!("[0] MiniUART is live!"); let uart = PL011Uart::default(); let mbox = Mailbox::default(); use crate::devices::console::ConsoleOps; CONSOLE.lock(|c| c.flush()); match uart.prepare(mbox, &gpio) { Ok(uart) => { CONSOLE.lock(|c| { c.replace_with(uart.into()); }); println!("[0] UART0 is live!"); } Err(_) => println!("[0] Error switching to PL011 UART, continue with MiniUART"), } } #[inline] pub fn kmain() -> ! { #[cfg(feature = "jtag")] jtag::wait_debugger(); init_mmu(); init_exception_traps(); #[cfg(not(feature = "noserial"))] init_uart_serial(); #[cfg(test)] test_main(); command_prompt(); reboot() } fn command_prompt() { 'cmd_loop: loop { let mut buf = [0u8; 64]; match CONSOLE.lock(|c| c.command_prompt(&mut buf)) { b"mmu" => init_mmu(), b"feats" => print_mmu_state_and_features(), #[cfg(not(feature = "noserial"))] b"uart" => init_uart_serial(), b"disp" => check_display_init(), b"trap" => check_data_abort_trap(), b"map" => arch::memory::print_layout(), b"led on" => set_led(true), b"led off" => set_led(false), b"help" => print_help(), b"end" => break 'cmd_loop, x => println!("[!] Unknown command {:?}, try 'help'", x), } } } fn print_help() { println!("Supported console commands:"); println!(" mmu - initialize MMU"); println!(" feats - print MMU state and supported features"); #[cfg(not(feature = "noserial"))] println!(" uart - try to reinitialize UART serial"); println!(" disp - try to init VC framebuffer and draw some text"); println!(" trap - trigger and recover from a data abort exception"); println!(" map - show kernel memory layout"); println!(" led [on|off] - change RPi LED status"); println!(" end - leave console and reset board"); } fn set_led(enable: bool) { let mut mbox = Mailbox::default(); let index = m
println!("Mailbox call returned error {}", e); println!("Mailbox contents: {:?}", mbox); }) .ok(); } fn reboot() -> ! { cfg_if! { if #[cfg(feature = "qemu")] { println!("Bye, shutting down QEMU"); qemu::semihosting::exit_success() } else { use crate::platform::rpi3::power::Power; println!("Bye, going to reset now"); Power::new().reset() } } } fn check_display_init() { display_graphics() .map_err(|e| { println!("Error in display: {}", e); }) .ok(); } fn display_graphics() -> Result<(), DrawError> { if let Ok(mut display) = VC::init_fb(800, 600, 32) { println!("Display created"); display.clear(Color::black()); println!("Display cleared"); display.rect(10, 10, 250, 250, Color::rgb(32, 96, 64)); display.draw_text(50, 50, "Hello there!", Color::rgb(128, 192, 255))?; let mut buf = [0u8; 64]; let s = write_to::show(&mut buf, format_args!("Display width {}", display.width)); if s.is_err() { display.draw_text(50, 150, "Error displaying", Color::red())? } else { display.draw_text(50, 150, s.unwrap(), Color::white())? } display.draw_text(150, 50, "RED", Color::red())?; display.draw_text(160, 60, "GREEN", Color::green())?; display.draw_text(170, 70, "BLUE", Color::blue())?; } Ok(()) } fn check_data_abort_trap() { let big_addr: u64 = 3 * 1024 * 1024 * 1024; unsafe { core::ptr::read_volatile(big_addr as *mut u64) }; println!("[i] Whoa! We recovered from an exception."); } #[cfg(test)] mod main_tests { use super::*; #[test_case] fn test_data_abort_trap() { check_data_abort_trap() } }
box.request(); let index = mbox.set_led_on(index, enable); let mbox = mbox.end(index); mbox.call(channel::PropertyTagsArmToVc) .map_err(|e| {
function_block-random_span
[ { "content": "/// Print the kernel memory layout.\n\npub fn print_layout() {\n\n println!(\"[i] Kernel memory layout:\");\n\n\n\n for i in KERNEL_VIRTUAL_LAYOUT.iter() {\n\n println!(\"{}\", i);\n\n }\n\n}\n", "file_path": "nucleus/src/arch/aarch64/memory/mod.rs", "rank": 0, "score":...
Rust
src/render/pipeline_2d.rs
RomainMazB/bevy_svg
da7acfe562a77151c33e995240d7ef40f803a5ff
use bevy::{ asset::Handle, core::FloatOrd, core_pipeline::Transparent2d, ecs::{entity::Entity, query::With, world::{FromWorld, World}, system::{Query, Res, ResMut},}, log::debug, render::{ mesh::Mesh, render_asset::RenderAssets, render_phase::{DrawFunctions, RenderPhase, SetItemPipeline}, render_resource::{ BlendState, ColorTargetState, ColorWrites, FragmentState, FrontFace, MultisampleState, PolygonMode, PrimitiveState, RenderPipelineCache, RenderPipelineDescriptor, Shader, SpecializedPipeline, SpecializedPipelines, TextureFormat, VertexAttribute, VertexBufferLayout, VertexFormat, VertexState, VertexStepMode, }, texture::BevyDefault, view::{ComputedVisibility, Msaa}, RenderWorld, }, sprite::{ DrawMesh2d, Mesh2dHandle, Mesh2dPipeline, Mesh2dPipelineKey, SetMesh2dBindGroup, SetMesh2dViewBindGroup, }, transform::components::GlobalTransform, }; use copyless::VecHelper; use crate::{render::SVG_2D_SHADER_HANDLE, svg::Svg}; #[derive(Default)] pub struct ExtractedSvgs2d { svgs: Vec<ExtractedSvg2d>, } #[derive(Clone)] pub struct ExtractedSvg2d { pub entity: Entity, pub mesh2d_handle: Mesh2dHandle, pub global_transform: GlobalTransform } pub fn extract_svg_2d( mut render_world: ResMut<RenderWorld>, query: Query<(Entity, &ComputedVisibility, &Mesh2dHandle, &GlobalTransform), With<Handle<Svg>>>, ) { debug!("Extracting `Svg`s from `World`."); let mut extracted_svgs = render_world.get_resource_mut::<ExtractedSvgs2d>().unwrap(); extracted_svgs.svgs.clear(); for (entity, computed_visibility, mesh2d_handle, global_transform) in query.iter() { if !computed_visibility.is_visible { continue; } extracted_svgs.svgs.alloc().init(ExtractedSvg2d { entity, mesh2d_handle: mesh2d_handle.clone(), global_transform: global_transform.clone(), }); } debug!("Extracted {} `Svg2d`s from `World` and inserted them into `RenderWorld`.", extracted_svgs.svgs.len()); } #[allow(clippy::too_many_arguments)] pub fn queue_svg_2d( transparent_draw_functions: Res<DrawFunctions<Transparent2d>>, svg_2d_pipeline: Res<Svg2dPipeline>, mut pipelines: ResMut<SpecializedPipelines<Svg2dPipeline>>, mut pipeline_cache: ResMut<RenderPipelineCache>, msaa: Res<Msaa>, render_meshes: Res<RenderAssets<Mesh>>, svgs_2d: ResMut<ExtractedSvgs2d>, mut views: Query<&mut RenderPhase<Transparent2d>>, ) { if svgs_2d.svgs.is_empty() { debug!("No `Svg2d`s found to queue."); return; } debug!("Queuing {} `Svg2d`s for drawing/rendering.", svgs_2d.svgs.len()); let mesh_key = Mesh2dPipelineKey::from_msaa_samples(msaa.samples); let draw_svg_2d = transparent_draw_functions .read() .get_id::<DrawSvg2d>() .unwrap(); for mut transparent_phase in views.iter_mut() { for svg2d in &svgs_2d.svgs { let mut mesh2d_key = mesh_key; if let Some(mesh) = render_meshes.get(&svg2d.mesh2d_handle.0) { mesh2d_key |= Mesh2dPipelineKey::from_primitive_topology(mesh.primitive_topology); } let pipeline_id = pipelines.specialize(&mut pipeline_cache, &svg_2d_pipeline, mesh2d_key); let mesh_z = svg2d.global_transform.translation.z; transparent_phase.add(Transparent2d { entity: svg2d.entity, draw_function: draw_svg_2d, pipeline: pipeline_id, sort_key: FloatOrd(mesh_z), batch_range: None, }); } } } pub type DrawSvg2d = ( SetItemPipeline, SetMesh2dViewBindGroup<0>, SetMesh2dBindGroup<1>, DrawMesh2d, ); pub struct Svg2dPipeline { mesh2d_pipeline: Mesh2dPipeline, } impl FromWorld for Svg2dPipeline { fn from_world(world: &mut World) -> Self { Self { mesh2d_pipeline: Mesh2dPipeline::from_world(world), } } } impl SpecializedPipeline for Svg2dPipeline { type Key = Mesh2dPipelineKey; fn specialize(&self, key: Self::Key) -> RenderPipelineDescriptor { let vertex_attributes = vec![ VertexAttribute { format: VertexFormat::Float32x3, offset: 16, shader_location: 0, }, VertexAttribute { format: VertexFormat::Float32x4, offset: 0, shader_location: 1, }, ]; let vertex_array_stride = 28; RenderPipelineDescriptor { vertex: VertexState { shader: SVG_2D_SHADER_HANDLE.typed::<Shader>(), entry_point: "vertex".into(), shader_defs: Vec::new(), buffers: vec![VertexBufferLayout { array_stride: vertex_array_stride, step_mode: VertexStepMode::Vertex, attributes: vertex_attributes, }], }, fragment: Some(FragmentState { shader: SVG_2D_SHADER_HANDLE.typed::<Shader>(), shader_defs: Vec::new(), entry_point: "fragment".into(), targets: vec![ColorTargetState { format: TextureFormat::bevy_default(), blend: Some(BlendState::ALPHA_BLENDING), write_mask: ColorWrites::ALL, }], }), layout: Some(vec![ self.mesh2d_pipeline.view_layout.clone(), self.mesh2d_pipeline.mesh_layout.clone(), ]), primitive: PrimitiveState { front_face: FrontFace::Cw, cull_mode: None, unclipped_depth: false, polygon_mode: PolygonMode::Fill, conservative: false, topology: key.primitive_topology(), strip_index_format: None, }, depth_stencil: None, multisample: MultisampleState { count: key.msaa_samples(), mask: !0, alpha_to_coverage_enabled: false, }, label: Some("svg_2d_pipeline".into()), } } }
use bevy::{ asset::Handle, core::FloatOrd, core_pipeline::Transparent2d, ecs::{entity::Entity, query::With, world::{FromWorld, World}, system::{Query, Res, ResMut},}, log::debug, render::{ mesh::Mesh, render_asset::RenderAssets, render_phase::{DrawFunctions, RenderPhase, SetItemPipeline}, render_resource::{ BlendState, ColorTargetState, ColorWrites, FragmentState, FrontFace, MultisampleState, PolygonMode, PrimitiveState, RenderPipelineCache, RenderPipelineDescriptor, Shader, SpecializedPipeline, SpecializedPipelines, TextureFormat, VertexAttribute, VertexBufferLayout, VertexFormat, VertexState, VertexStepMode, }, texture::BevyDefault, view::{ComputedVisibility, Msaa}, RenderWorld, }, sprite::{ DrawMesh2d, Mesh2dHandle, Mesh2dPipeline, Mesh2dPipelineKey, SetMesh2dBindGroup, SetMesh2dViewBindGroup, }, transform::components::GlobalTransform, }; use copyless::VecHelper; use crate::{render::SVG_2D_SHADER_HANDLE, svg::Svg}; #[derive(Default)] pub struct ExtractedSvgs2d { svgs: Vec<ExtractedSvg2d>, } #[derive(Clone)] pub struct ExtractedSvg2d { pub entity: Entity, pub mesh2d_handle: Mesh2dHandle, pub global_transform: GlobalTransform } pub fn extract_svg_2d( mut render_world: ResMut<RenderWorld>, query: Query<(Entity, &ComputedVisibility, &Mesh2dHandle, &GlobalTransform), With<Handle<Svg>>>, ) { debug!("Extracting `Svg`s from `World`."); let mut extracted_svgs = render_world.get_resource_mut::<ExtractedSvgs2d>().unwrap(); extracted_svgs.svgs.clear(); for (entity, computed_visibility, mesh2d_handle, global_transform) in query.iter() { if !computed_visibility.is_visible { continue; } extracted_svgs.svgs.alloc().init(ExtractedSvg2d { entity, mesh2d_handle: mesh2d_handle.clone(), global_transform: global_transform.clone(), }); } debug!("Extracted {} `Svg2d`s from `World` and inserted them into `RenderWorld`.", extracted_svgs.svgs.len()); } #[allow(clippy::too_many_arguments)] pub fn queue_svg_2d( transparent_draw_functions: Res<DrawFunctions<Transparent2d>>, svg_2d_pipeline: Res<Svg2dPipeline>, mut pipelines: ResMut<SpecializedPipelines<Svg2dPipeline>>, mut pipeline_cache: ResMut<RenderPipelineCache>, msaa: Res<Msaa>, render_meshes: Res<RenderAssets<Mesh>>, svgs_2d: ResMut<ExtractedSvgs2d>, mut views: Query<&mut RenderPhase<Transparent2d>>, ) { if svgs_2d.svgs.is_empty() { debug!("No `Svg2d`s found to queue."); return; } debug!("Queuing {} `Svg2d`s for drawing/rendering.", svgs_2d.svgs.len()); let mesh_key = Mesh2dPipelineKey::from_msaa_samples(msaa.samples); let draw_svg_2d = transparent_draw_functions .read() .get_id::<DrawSvg2d>() .unwrap(); for mut transparent_phase in views.iter_mut() { for svg2d in &svgs_2d.svgs { let mut mesh2d_key = mesh_key; if let Some(mesh) = render_meshes.get(&svg2d.mesh2d_handle.0) { mesh2d_key |= Mesh2dPipelineKey::from_primitive_topology(mesh.primitive_topology); } let pipeline_id = pipelines.specialize(&mut pipeline_cache, &svg_2d_pipeline, mesh2d_key); let mesh_z = svg2d.global_transform.translation.z; transparent_phase.add(Transparent2d { entity: svg2d.entity, draw_function: draw_svg_2d, pipeline: pipeline_id, sort_key: FloatOrd(mesh_z), batch_range: None, }); } } } pub type DrawSvg2d = ( SetItemPipeline, SetMesh2dViewBindGroup<0>, SetMesh2dBindGroup<1>, DrawMesh2d, ); pub struct Svg2dPipeline { mesh2d_pipeline: Mesh2dPipeline, } impl FromWorld for Svg2dPipeline { fn from_world(world: &mut World) -> Self { Self { mesh2d_pipeline: Mesh2dPipeline::from_world(world), } } } impl SpecializedPipeline for Svg2dPipeline { type Key = Mesh2dPipelineKey; fn specialize(&self, key: Self::Key) -> RenderPipelineDescriptor { let vertex_attributes = vec![ VertexAttribute { format: VertexFormat::Float32x3, offset: 16, shader_location: 0, }, VertexAttribute { format: VertexFormat::Float32x4, offset: 0, shader_location: 1, }, ]; let vertex_array_stride = 28; RenderPipelineDescriptor { vertex: VertexState { shader: SVG_2D_SHADER_HANDLE.typed::<Shader>(), entry_point: "vertex".into(), shader_defs: Vec::new(), buffers: vec![VertexBufferLayout { array_stride: vertex_array_stride, step_mode: VertexStepMode::Vertex, attributes: vertex_attributes, }], }, fragment: Some(FragmentState { shader: SVG_2D_SHADER_HANDLE.typed::<Shader>(), shader_defs: Vec::new(), entry_point: "fragment".into(), targets: vec![ColorTargetState { format: TextureFormat::bevy_default(), blend: Some(BlendState::ALPHA_BLENDING), write_mask: ColorWrites::ALL, }], }), layout:
, primitive: PrimitiveState { front_face: FrontFace::Cw, cull_mode: None, unclipped_depth: false, polygon_mode: PolygonMode::Fill, conservative: false, topology: key.primitive_topology(), strip_index_format: None, }, depth_stencil: None, multisample: MultisampleState { count: key.msaa_samples(), mask: !0, alpha_to_coverage_enabled: false, }, label: Some("svg_2d_pipeline".into()), } } }
Some(vec![ self.mesh2d_pipeline.view_layout.clone(), self.mesh2d_pipeline.mesh_layout.clone(), ])
call_expression
[ { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn queue_svg_3d(\n\n transparent_draw_functions: Res<DrawFunctions<Transparent3d>>,\n\n svg_3d_pipeline: Res<Svg3dPipeline>,\n\n mut pipelines: ResMut<SpecializedPipelines<Svg3dPipeline>>,\n\n mut pipeline_cache: ResMut<RenderPipelineCache>,\...
Rust
src/cmd/env.rs
wang-q/garr
50c1ecc08e2e4f854fe4186882a738aaa3d3e41d
use clap::*; use garr::*; use std::collections::HashMap; use std::fs; use tera::{Context, Tera}; pub fn make_subcommand<'a, 'b>() -> App<'a, 'b> { SubCommand::with_name("env") .about("Create a .env file") .after_help( r#" Default values: * REDIS_HOST - localhost * REDIS_PORT - 6379 * REDIS_PASSWORD - * REDIS_TLS - false "#, ) .arg(Arg::with_name("all").long("all").help("Create all scripts")) .arg( Arg::with_name("outfile") .short("o") .long("outfile") .takes_value(true) .default_value("garr.env") .empty_values(false) .help("Output filename. [stdout] for screen"), ) } pub fn execute(args: &ArgMatches) -> std::result::Result<(), std::io::Error> { let mut context = Context::new(); match envy::from_env::<Config>() { Ok(config) => { context.insert("host", &config.redis_host); context.insert("port", &config.redis_port); context.insert("password", &config.redis_password); context.insert("tls", &config.redis_tls); } Err(error) => panic!("{:#?}", error), } let mut opt = HashMap::new(); opt.insert("outfile", args.value_of("outfile").unwrap()); context.insert("opt", &opt); eprintln!("Create {}", opt.get("outfile").unwrap()); let mut tera = Tera::default(); tera.add_raw_templates(vec![("t", include_str!("../../templates/garr.tera.env"))]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(opt.get("outfile").unwrap(), &vec![rendered.as_str()])?; if args.is_present("all") { gen_peak(&context)?; gen_plot_xy(&context)?; fs::create_dir_all("sqls/ddl")?; gen_ddl_ctg(&context)?; gen_ddl_rsw(&context)?; gen_dql_summary(&context)?; gen_dql_rsw(&context)?; } Ok(()) } fn gen_peak(context: &Context) -> std::result::Result<(), std::io::Error> { let outname = "peak.R"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![("t", include_str!("../../templates/peak.tera.R"))]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; Ok(()) } fn gen_plot_xy(context: &Context) -> std::result::Result<(), std::io::Error> { let outname = "plot_xy.R"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![("t", include_str!("../../templates/plot_xy.tera.R"))]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; Ok(()) } fn gen_ddl_ctg(context: &Context) -> std::result::Result<(), std::io::Error> { let outname = "sqls/ddl/ctg.sql"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![( "t", include_str!("../../templates/ddl/ctg.tera.sql"), )]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; Ok(()) } fn gen_ddl_rsw(context: &Context) -> std::result::Result<(), std::io::Error> { let outname = "sqls/ddl/rsw.sql"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![( "t", include_str!("../../templates/ddl/rsw.tera.sql"), )]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; Ok(()) } fn gen_dql_summary(context: &Context) -> std::result::Result<(), std::io::Error> { let outname = "sqls/summary.sql"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![( "t", include_str!("../../templates/dql/summary.tera.sql"), )]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; let outname = "sqls/summary-type.sql"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![( "t", include_str!("../../templates/dql/summary-type.tera.sql"), )]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; Ok(()) } fn gen_dql_rsw(context: &Context) -> std::result::Result<(), std::io::Error> { let outname = "sqls/rsw-distance.sql"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![( "t", include_str!("../../templates/dql/rsw-distance.tera.sql"), )]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; let outname = "sqls/rsw-distance-tag.sql"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![( "t", include_str!("../../templates/dql/rsw-distance-tag.tera.sql"), )]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; Ok(()) }
use clap::*; use garr::*; use std::collections::HashMap; use std::fs; use tera::{Context, Tera}; pub fn make_subcommand<'a, 'b>() -> App<'a, 'b> { SubCommand::with_name("env") .about("Create a .env file") .after_help( r#" Default values: * REDIS_HOST - localhost * REDIS_PORT - 6379 * REDIS_PASSWORD - * REDIS_TLS - false "#, ) .arg(Arg::with_name("all").long("all").help("Create all scripts")) .arg( Arg::with_name("outfile") .short("o") .long("outfile") .takes_value(true) .default_value("garr.env") .empty_values(false) .help("Output filename. [stdout] for screen"), ) } pub fn execute(args: &ArgMatches) -> std::result::Result<(), std::io::Error> { let mut context = Context::new(); match envy::from_env::<Config>() { Ok(config) => { context.insert("host", &config.redis_host); context.insert("port", &config.redis_port); context.insert("password", &config.redis_password); context.insert("tls", &config.redis_tls); } Err(error) => panic!("{:#?}", error), } let mut opt = HashMap::new(); opt.insert("outfile", args.value_of("outfile").unwrap()); context.insert("opt", &opt); eprintln!("Create {}", opt.get("outfile").unwrap()); let mut tera = Tera::default(); tera.add_raw_templates(vec![("t", include_str!("../../templates/garr.tera.env"))]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(opt.get("outfile").unwrap(), &vec![rendered.as_str()])?; if args.is_present("all") { gen_peak(&context)?; gen_plot_xy(&context)?; fs::create_dir_all("sqls/ddl")?; gen_ddl_ctg(&context)?; gen_ddl_rsw(&context)?; gen_dql_summary(&context)?; gen_dql_rsw(&context)?; } Ok(()) } fn gen_peak(context: &Context) -> std::result::Result<(), std::io::Error> { let outname = "peak.R"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![("t", include_str!("../../templates/peak.tera.R"))]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; Ok(()) } fn gen_plot_xy(context: &Context) -> std::result::Result<(), std::io::Error> { let outname = "plot_xy.R"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![("t", include_str!("../../templates/plot_xy.tera.R"))]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; Ok(()) } fn gen_ddl_ctg(context: &Context) -> std::result::Result<(), std::io::Error> { let outname = "sqls/ddl/ctg.sql"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![( "t", include_str!("../../templates/ddl/ctg.tera.sql"), )]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; Ok(()) } fn gen_ddl_rsw(context: &Context) -> std::result::Result<(), std::io::Error> { let out
ec![( "t", include_str!("../../templates/ddl/rsw.tera.sql"), )]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; Ok(()) } fn gen_dql_summary(context: &Context) -> std::result::Result<(), std::io::Error> { let outname = "sqls/summary.sql"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![( "t", include_str!("../../templates/dql/summary.tera.sql"), )]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; let outname = "sqls/summary-type.sql"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![( "t", include_str!("../../templates/dql/summary-type.tera.sql"), )]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; Ok(()) } fn gen_dql_rsw(context: &Context) -> std::result::Result<(), std::io::Error> { let outname = "sqls/rsw-distance.sql"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![( "t", include_str!("../../templates/dql/rsw-distance.tera.sql"), )]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; let outname = "sqls/rsw-distance-tag.sql"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![( "t", include_str!("../../templates/dql/rsw-distance-tag.tera.sql"), )]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; Ok(()) }
name = "sqls/ddl/rsw.sql"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(v
function_block-random_span
[ { "content": "// command implementation\n\npub fn execute(args: &ArgMatches) -> std::result::Result<(), std::io::Error> {\n\n // redis connection\n\n let mut conn = connect();\n\n\n\n // processing each file\n\n for infile in args.values_of(\"infiles\").unwrap() {\n\n let reader = reader(infi...
Rust
cita-chain/types/src/receipt.rs
Pencil-Yao/cita
bcd00dc848fd2ca4b1e72d57f5f0e059bb2d3828
use super::Bytes; use std::str::FromStr; use crate::block_number::BlockNumber; use crate::errors::ReceiptError; use crate::log::{LocalizedLog, Log}; use cita_types::traits::LowerHex; use cita_types::{Address, Bloom as LogBloom, H256, U256}; use jsonrpc_types::rpc_types::Receipt as RpcReceipt; use libproto::executor::{Receipt as ProtoReceipt, ReceiptErrorWithOption, StateRoot}; use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp}; #[derive(Serialize, Deserialize, Default, Debug, Clone, PartialEq, Eq)] pub struct Receipt { pub state_root: Option<H256>, pub quota_used: U256, pub log_bloom: LogBloom, pub logs: Vec<Log>, pub error: Option<ReceiptError>, pub account_nonce: U256, pub transaction_hash: H256, } impl Receipt { pub fn new( state_root: Option<H256>, quota_used: U256, logs: Vec<Log>, error: Option<ReceiptError>, account_nonce: U256, transaction_hash: H256, ) -> Receipt { Receipt { state_root, quota_used, log_bloom: logs.iter().fold(LogBloom::default(), |b, l| b | l.bloom()), logs, error, account_nonce, transaction_hash, } } pub fn protobuf(&self) -> ProtoReceipt { let mut receipt_proto = ProtoReceipt::new(); let mut state_root_option = StateRoot::new(); let mut receipt_error_with_option = ReceiptErrorWithOption::new(); if let Some(state_root) = self.state_root { state_root_option.set_state_root(state_root.to_vec()); receipt_proto.set_state_root(state_root_option); } if let Some(error) = self.error { receipt_error_with_option.set_error(error.protobuf()); receipt_proto.set_error(receipt_error_with_option); } receipt_proto.set_quota_used(self.quota_used.lower_hex()); receipt_proto.set_log_bloom(self.log_bloom.to_vec()); receipt_proto.logs = self .logs .clone() .into_iter() .map(|log_entry| log_entry.protobuf()) .collect(); receipt_proto.set_account_nonce(self.account_nonce.as_u64()); receipt_proto.set_transaction_hash(self.transaction_hash.to_vec()); receipt_proto } } impl From<ProtoReceipt> for Receipt { fn from(receipt: ProtoReceipt) -> Self { let state_root = if receipt.state_root.is_some() { Some(H256::from_slice( receipt.clone().take_state_root().get_state_root(), )) } else { None }; let quota_used: U256 = U256::from_str(receipt.get_quota_used()).unwrap(); let account_nonce: U256 = U256::from(receipt.get_account_nonce()); let transaction_hash: H256 = H256::from_slice(receipt.get_transaction_hash()); let mut error = None; let logs = receipt .get_logs() .iter() .map(|log_entry| { let address: Address = Address::from_slice(log_entry.get_address()); let topics: Vec<H256> = log_entry .get_topics() .iter() .map(|topic| H256::from_slice(topic)) .collect(); let data: Bytes = Bytes::from(log_entry.get_data()); Log { address, topics, data, } }) .collect(); if receipt.error.is_some() { error = Some(ReceiptError::from_proto( receipt.clone().take_error().get_error(), )); } Receipt::new( state_root, quota_used, logs, error, account_nonce, transaction_hash, ) } } impl Encodable for Receipt { fn rlp_append(&self, s: &mut RlpStream) { if let Some(ref root) = self.state_root { s.begin_list(7); s.append(root); } else { s.begin_list(6); } s.append(&self.quota_used); s.append(&self.log_bloom); s.append_list(&self.logs); s.append(&self.error); s.append(&self.account_nonce); s.append(&self.transaction_hash); } } impl Decodable for Receipt { fn decode(rlp: &UntrustedRlp) -> Result<Self, DecoderError> { if rlp.item_count()? == 6 { Ok(Receipt { state_root: None, quota_used: rlp.val_at(0)?, log_bloom: rlp.val_at(1)?, logs: rlp.list_at(2)?, error: rlp.val_at(3)?, account_nonce: rlp.val_at(4)?, transaction_hash: rlp.val_at(5)?, }) } else { Ok(Receipt { state_root: Some(rlp.val_at(0)?), quota_used: rlp.val_at(1)?, log_bloom: rlp.val_at(2)?, logs: rlp.list_at(3)?, error: rlp.val_at(4)?, account_nonce: rlp.val_at(5)?, transaction_hash: rlp.val_at(6)?, }) } } } #[derive(Debug, Clone)] pub struct RichReceipt { pub transaction_hash: H256, pub transaction_index: usize, pub block_hash: H256, pub block_number: BlockNumber, pub cumulative_quota_used: U256, pub quota_used: U256, pub contract_address: Option<Address>, pub logs: Vec<LocalizedLog>, pub log_bloom: LogBloom, pub state_root: Option<H256>, pub error: Option<ReceiptError>, } impl Into<RpcReceipt> for RichReceipt { fn into(self) -> RpcReceipt { RpcReceipt { transaction_hash: Some(self.transaction_hash), transaction_index: Some(self.transaction_index.into()), block_hash: Some(self.block_hash), block_number: Some(self.block_number.into()), cumulative_quota_used: self.cumulative_quota_used, quota_used: Some(self.quota_used), contract_address: self.contract_address.map(Into::into), logs: self.logs.into_iter().map(Into::into).collect(), state_root: self.state_root.map(Into::into), logs_bloom: self.log_bloom, error_message: self.error.map(ReceiptError::description), } } } #[cfg(test)] mod tests { use super::*; use crate::log::Log; #[test] fn test_no_state_root() { let r = Receipt::new( None, 0x40cae.into(), vec![Log { address: "dcf421d093428b096ca501a7cd1a740855a7976f".into(), topics: vec![], data: vec![0u8; 32], }], None, 1.into(), "2f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee".into(), ); let encoded = ::rlp::encode(&r); println!("encode ok"); let decoded: Receipt = ::rlp::decode(&encoded); println!("decoded: {:?}", decoded); assert_eq!(decoded, r); } #[test] fn test_basic() { let r = Receipt::new( Some("2f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee".into()), 0x40cae.into(), vec![Log { address: "dcf421d093428b096ca501a7cd1a740855a7976f".into(), topics: vec![], data: vec![0u8; 32], }], None, 1.into(), "2f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee".into(), ); let encoded = ::rlp::encode(&r); let decoded: Receipt = ::rlp::decode(&encoded); println!("decoded: {:?}", decoded); assert_eq!(decoded, r); } #[test] fn test_with_error() { let r = Receipt::new( Some("2f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee".into()), 0x40cae.into(), vec![Log { address: "dcf421d093428b096ca501a7cd1a740855a7976f".into(), topics: vec![], data: vec![0u8; 32], }], Some(ReceiptError::NoTransactionPermission), 1.into(), "2f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee".into(), ); let encoded = ::rlp::encode(&r); let decoded: Receipt = ::rlp::decode(&encoded); println!("decoded: {:?}", decoded); assert_eq!(decoded, r); } }
use super::Bytes; use std::str::FromStr; use crate::block_number::BlockNumber; use crate::errors::ReceiptError; use crate::log::{LocalizedLog, Log}; use cita_types::traits::LowerHex; use cita_types::{Address, Bloom as LogBloom, H256, U256}; use jsonrpc_types::rpc_types::Receipt as RpcReceipt; use libproto::executor::{Receipt as ProtoReceipt, ReceiptErrorWithOption, StateRoot}; use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp}; #[derive(Serialize, Deserialize, Default, Debug, Clone, PartialEq, Eq)] pub struct Receipt { pub state_root: Option<H256>, pub quota_used: U256, pub log_bloom: LogBloom, pub logs: Vec<Log>, pub error: Option<ReceiptError>, pub account_nonce: U256, pub transaction_hash: H256, } impl Receipt { pub fn new( state_root: Option<H256>, quota_used: U256, logs: Vec<Log>, error: Option<ReceiptError>, account_nonce: U256, transaction_hash: H256, ) -> Receipt { Receipt { state_root, quota_used, log_bloom: logs.iter().fold(LogBloom::default(), |b, l| b | l.bloom()), logs, error, account_nonce, transaction_hash, } } pub fn protobuf(&self) -> ProtoReceipt { let mut receipt_proto = ProtoReceipt::new(); let mut state_root_option = StateRoot::new(); let mut receipt_error_with_option = ReceiptErrorWithOption::new(); if let Some(state_root) = self.state_root { state_root_option.set_state_root(state_root.to_vec()); receipt_proto.set_state_root(state_root_option); } if let Some(error) = self.error { receipt_error_with_option.set_error(error.protobuf()); receipt_proto.set_error(receipt_error_with_option); } receipt_proto.set_quota_used(self.quota_used.lower_hex()); receipt_proto.set_log_bloom(self.log_bloom.to_vec()); receipt_proto.logs = self .
} impl From<ProtoReceipt> for Receipt { fn from(receipt: ProtoReceipt) -> Self { let state_root = if receipt.state_root.is_some() { Some(H256::from_slice( receipt.clone().take_state_root().get_state_root(), )) } else { None }; let quota_used: U256 = U256::from_str(receipt.get_quota_used()).unwrap(); let account_nonce: U256 = U256::from(receipt.get_account_nonce()); let transaction_hash: H256 = H256::from_slice(receipt.get_transaction_hash()); let mut error = None; let logs = receipt .get_logs() .iter() .map(|log_entry| { let address: Address = Address::from_slice(log_entry.get_address()); let topics: Vec<H256> = log_entry .get_topics() .iter() .map(|topic| H256::from_slice(topic)) .collect(); let data: Bytes = Bytes::from(log_entry.get_data()); Log { address, topics, data, } }) .collect(); if receipt.error.is_some() { error = Some(ReceiptError::from_proto( receipt.clone().take_error().get_error(), )); } Receipt::new( state_root, quota_used, logs, error, account_nonce, transaction_hash, ) } } impl Encodable for Receipt { fn rlp_append(&self, s: &mut RlpStream) { if let Some(ref root) = self.state_root { s.begin_list(7); s.append(root); } else { s.begin_list(6); } s.append(&self.quota_used); s.append(&self.log_bloom); s.append_list(&self.logs); s.append(&self.error); s.append(&self.account_nonce); s.append(&self.transaction_hash); } } impl Decodable for Receipt { fn decode(rlp: &UntrustedRlp) -> Result<Self, DecoderError> { if rlp.item_count()? == 6 { Ok(Receipt { state_root: None, quota_used: rlp.val_at(0)?, log_bloom: rlp.val_at(1)?, logs: rlp.list_at(2)?, error: rlp.val_at(3)?, account_nonce: rlp.val_at(4)?, transaction_hash: rlp.val_at(5)?, }) } else { Ok(Receipt { state_root: Some(rlp.val_at(0)?), quota_used: rlp.val_at(1)?, log_bloom: rlp.val_at(2)?, logs: rlp.list_at(3)?, error: rlp.val_at(4)?, account_nonce: rlp.val_at(5)?, transaction_hash: rlp.val_at(6)?, }) } } } #[derive(Debug, Clone)] pub struct RichReceipt { pub transaction_hash: H256, pub transaction_index: usize, pub block_hash: H256, pub block_number: BlockNumber, pub cumulative_quota_used: U256, pub quota_used: U256, pub contract_address: Option<Address>, pub logs: Vec<LocalizedLog>, pub log_bloom: LogBloom, pub state_root: Option<H256>, pub error: Option<ReceiptError>, } impl Into<RpcReceipt> for RichReceipt { fn into(self) -> RpcReceipt { RpcReceipt { transaction_hash: Some(self.transaction_hash), transaction_index: Some(self.transaction_index.into()), block_hash: Some(self.block_hash), block_number: Some(self.block_number.into()), cumulative_quota_used: self.cumulative_quota_used, quota_used: Some(self.quota_used), contract_address: self.contract_address.map(Into::into), logs: self.logs.into_iter().map(Into::into).collect(), state_root: self.state_root.map(Into::into), logs_bloom: self.log_bloom, error_message: self.error.map(ReceiptError::description), } } } #[cfg(test)] mod tests { use super::*; use crate::log::Log; #[test] fn test_no_state_root() { let r = Receipt::new( None, 0x40cae.into(), vec![Log { address: "dcf421d093428b096ca501a7cd1a740855a7976f".into(), topics: vec![], data: vec![0u8; 32], }], None, 1.into(), "2f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee".into(), ); let encoded = ::rlp::encode(&r); println!("encode ok"); let decoded: Receipt = ::rlp::decode(&encoded); println!("decoded: {:?}", decoded); assert_eq!(decoded, r); } #[test] fn test_basic() { let r = Receipt::new( Some("2f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee".into()), 0x40cae.into(), vec![Log { address: "dcf421d093428b096ca501a7cd1a740855a7976f".into(), topics: vec![], data: vec![0u8; 32], }], None, 1.into(), "2f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee".into(), ); let encoded = ::rlp::encode(&r); let decoded: Receipt = ::rlp::decode(&encoded); println!("decoded: {:?}", decoded); assert_eq!(decoded, r); } #[test] fn test_with_error() { let r = Receipt::new( Some("2f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee".into()), 0x40cae.into(), vec![Log { address: "dcf421d093428b096ca501a7cd1a740855a7976f".into(), topics: vec![], data: vec![0u8; 32], }], Some(ReceiptError::NoTransactionPermission), 1.into(), "2f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee".into(), ); let encoded = ::rlp::encode(&r); let decoded: Receipt = ::rlp::decode(&encoded); println!("decoded: {:?}", decoded); assert_eq!(decoded, r); } }
logs .clone() .into_iter() .map(|log_entry| log_entry.protobuf()) .collect(); receipt_proto.set_account_nonce(self.account_nonce.as_u64()); receipt_proto.set_transaction_hash(self.transaction_hash.to_vec()); receipt_proto }
function_block-function_prefix_line
[ { "content": "fn accrue_log(bloom: &mut Bloom, log: &Log) {\n\n bloom.accrue(BloomInput::Raw(&log.address.0));\n\n for topic in &log.topics {\n\n let input = BloomInput::Hash(&topic.0);\n\n bloom.accrue(input);\n\n }\n\n}\n\n\n", "file_path": "cita-executor/core/src/cita_executive.rs"...
Rust
src/gameboy/cpu/register.rs
Hanaasagi/NGC-224
24a3c439148ffef0930e19c9d88c68a9164a5459
use super::super::Term; #[derive(Default, Debug, Clone)] #[allow(non_snake_case)] pub struct Register { A: u8, B: u8, C: u8, D: u8, E: u8, F: u8, H: u8, L: u8, PC: u16, SP: u16, } impl Register { pub fn new() -> Self { Self::default() } pub fn new_from_debug_string(s: &str) -> Self { let mut reg = Self::new(); let s = &s[11..s.len() - 2]; for field in s.split(", ") { let tmp: Vec<&str> = field.split(": ").collect(); let name = tmp[0].to_uppercase(); let value: u16 = tmp[1].parse().unwrap(); match &name as &str { "A" => reg.A = value as u8, "B" => reg.B = value as u8, "C" => reg.C = value as u8, "D" => reg.D = value as u8, "E" => reg.E = value as u8, "F" => reg.F = value as u8, "H" => reg.H = value as u8, "L" => reg.L = value as u8, "PC" => reg.PC = value, "SP" => reg.SP = value, _ => panic!("{} is unknown field", name), } } reg } pub fn init(&mut self, term: Term) { match term { Term::GB => { self.A = 0x01; } Term::GBP => { self.A = 0xff; } Term::GBC => { self.A = 0x11; } Term::SGB => { self.A = 0x01; } } self.B = 0x00; self.C = 0x13; self.D = 0x00; self.E = 0xD8; self.F = 0xB0; self.H = 0x01; self.L = 0x4D; self.PC = 0x0100; self.SP = 0xFFFE; } } #[allow(non_snake_case)] impl Register { #[inline] pub fn get_A(&self) -> u8 { self.A } #[inline] pub fn get_B(&self) -> u8 { self.B } #[inline] pub fn get_C(&self) -> u8 { self.C } #[inline] pub fn get_D(&self) -> u8 { self.D } #[inline] pub fn get_E(&self) -> u8 { self.E } #[inline] pub fn get_H(&self) -> u8 { self.H } #[inline] pub fn get_L(&self) -> u8 { self.L } #[inline] pub fn get_PC(&self) -> u16 { self.PC } #[inline] pub fn get_SP(&self) -> u16 { self.SP } #[inline] pub fn incr_PC(&mut self) { self.PC += 1; } #[inline] pub fn get_AF(&self) -> u16 { (u16::from(self.A) << 8) | u16::from(self.F) } #[inline] pub fn get_BC(&self) -> u16 { (u16::from(self.B) << 8) | u16::from(self.C) } #[inline] pub fn get_DE(&self) -> u16 { (u16::from(self.D) << 8) | u16::from(self.E) } #[inline] pub fn get_HL(&self) -> u16 { (u16::from(self.H) << 8) | u16::from(self.L) } } #[allow(non_snake_case)] impl Register { #[inline] pub fn set_A(&mut self, v: u8) { self.A = v } #[inline] pub fn set_B(&mut self, v: u8) { self.B = v } #[inline] pub fn set_C(&mut self, v: u8) { self.C = v } #[inline] pub fn set_D(&mut self, v: u8) { self.D = v } #[inline] pub fn set_E(&mut self, v: u8) { self.E = v } #[inline] pub fn set_H(&mut self, v: u8) { self.H = v } #[inline] pub fn set_L(&mut self, v: u8) { self.L = v } #[inline] pub fn set_AF(&mut self, v: u16) { self.A = (v >> 8) as u8; self.F = (v & 0x00f0) as u8; } #[inline] pub fn set_BC(&mut self, v: u16) { self.B = (v >> 8) as u8; self.C = (v & 0x00ff) as u8; } #[inline] pub fn set_DE(&mut self, v: u16) { self.D = (v >> 8) as u8; self.E = (v & 0x00ff) as u8; } #[inline] pub fn set_HL(&mut self, v: u16) { self.H = (v >> 8) as u8; self.L = (v & 0x00ff) as u8; } #[inline] pub fn incr_HL(&mut self) { self.set_HL(self.get_HL().wrapping_add(1)); } #[inline] pub fn set_PC(&mut self, v: u16) { self.PC = v } #[inline] pub fn set_SP(&mut self, v: u16) { self.SP = v } } impl Register { #[inline] pub fn is_flag_set(&self, flag: Flag) -> bool { (self.F & flag.value()) != 0 } pub fn set_flag(&mut self, flag: Flag) { self.F = self.F | (flag.value()); } pub fn unset_flag(&mut self, flag: Flag) { self.F = self.F & !(flag.value()) } pub fn reverse_flag(&mut self, flag: Flag) { if self.is_flag_set(flag.clone()) { self.unset_flag(flag); } else { self.set_flag(flag); } } } #[derive(Clone, Debug)] pub enum Flag { Zero = 0b1000_0000, Sub = 0b0100_0000, HalfCarry = 0b0010_0000, Carry = 0b0001_0000, } impl Flag { pub fn into_value(self) -> u8 { self as u8 } pub fn value(&self) -> u8 { self.clone() as u8 } } #[rustfmt::skip] #[derive(Clone)] pub enum IntFlag { VBlank = 0b0000, LCDStat = 0b0001, Timer = 0b0010, Serial = 0b0011, Joypad = 0b0100, } pub struct IntReg { pub data: u8, } impl IntReg { pub fn new() -> Self { Self { data: 0x00 } } pub fn req(&mut self, flag: IntFlag) { self.data |= 1 << flag as u8; } }
use super::super::Term; #[derive(Default, Debug, Clone)] #[allow(non_snake_case)] pub struct Register { A: u8, B: u8, C: u8, D: u8, E: u8, F: u8, H: u8, L: u8, PC: u16, SP: u16, } impl Register { pub fn new() -> Self { Self::default() } pub fn new_from_debug_string(s: &str) -> Self { let mut reg = Self::new(); let s = &s[11..s.len() - 2]; for field in s.split(", ") { let tmp: Vec<&str> = field.split(": ").collect(); let name = tmp[0].to_uppercase(); let value: u16 = tmp[1].parse().unwrap(); match &name as &str { "A" => reg.A = value as u8, "B" => reg.B = value as u8, "C" => reg.C = value as u8, "D" => reg.D = value as u8, "E" => reg.E = value as u8, "F" => reg.F = value as u8, "H" => reg.H = value as u8, "L" => reg.L = value as u8, "PC" => reg.PC = value, "SP" => reg.SP = value, _ => panic!("{} is unknown field", name), } } reg } pub fn init(&mut self, term: Term) { match term { Term::GB => { self.A = 0x01; } Term::GBP => { self.A = 0xff; } Term::GBC => { self.A = 0x11; } Term::SGB => { self.A = 0x01; } } self.B = 0x00; self.C = 0x13; self.D = 0x00; self.E = 0xD8; self.F = 0xB0; self.H = 0x01; self.L = 0x4D; self.PC = 0x0100; self.SP = 0xFFFE; } } #[allow(non_snake_case)] impl Register { #[inline] pub fn get_A(&self) -> u8 { self.A } #[inline] pub fn get_B(&self) -> u8 { self.B } #[inline] pub fn get_C(&self) -> u8 { self.C } #[inline] pub fn get_D(&self) -> u8 { self.D } #[inline] pub fn get_E(&self) -> u8 { self.E } #[inline] pub fn get_H(&self) -> u8 { self.H } #[inline] pub fn get_L(&self) -> u8 { self.L } #[inline] pub fn get_PC(&self) -> u16 { self.PC } #[inline] pub fn get_SP(&self) -> u16 { self.SP } #[inline] pub fn incr_PC(&mut self) { self.PC += 1; } #[inline] pub fn get_AF(&self) -> u16 { (u16::from(self.A) << 8) | u16::from(self.F) } #[inline] pub fn get_BC(&self) -> u16 { (u16::from(self.B) << 8) | u16::from(self.C) } #[inline] pub fn get_DE(&self) -> u16 { (u16::from(self.D) << 8) | u16::from(self.E) } #[inline] pub fn get_HL(&self) -> u16 { (u16::from(self.H) << 8) | u16::from(self.L) } } #[allow(non_snake_case)] impl Register { #[inline] pub fn set_A(&mut self, v: u8) { self.A = v } #[inline] pub fn set_B(&mut self, v: u8) { self.B = v } #[inline] pub fn set_C(&mut self, v: u8) { self.C = v } #[inline] pub fn set_D(&mut self, v: u8) { self.D = v } #[inline] pub fn set_E(&mut self, v: u8) { self.E = v } #[inline] pub fn set_H(&mut self, v: u8) { self.H = v } #[inline] pub fn set_L(&mut self, v: u8) { self.L = v } #[inline] pub fn set_AF(&mut self, v: u16) { self.A = (v >> 8) as u8; self.F = (v & 0x00f0) as u8; } #[inline] pub fn set_BC(&mut self, v: u16) { self.B = (v >> 8) as u8; self.C = (v & 0x00ff) as u8; } #[inline] pub fn set_DE(&mut self, v: u16) { self.D = (v >> 8) as u8; self.E = (v & 0x00ff) as u8; } #[inline] pub fn set_HL(&mut self, v: u16) { self.H = (v >> 8) as u8; self.L = (v & 0x00ff) as u8; } #[inline] pub fn incr_HL(&mut self) { self.set_HL(self.get_HL().wrapping_add(1)); } #[inline] pub fn set_PC(&mut self, v: u16) { self.PC = v } #[inline] pub fn set_SP(&mut self, v: u16) { self.SP = v } } impl Register { #[inline] pub fn is_flag_set(&self, flag: Flag) -> bool { (self.F & flag.value()) != 0 } pub fn set_flag(&mut self, flag: Flag) { self.F = self.F | (flag.value()); } pub fn unset_flag(&mut self, flag: Flag) { self.F = self.F & !(flag.value()) }
} #[derive(Clone, Debug)] pub enum Flag { Zero = 0b1000_0000, Sub = 0b0100_0000, HalfCarry = 0b0010_0000, Carry = 0b0001_0000, } impl Flag { pub fn into_value(self) -> u8 { self as u8 } pub fn value(&self) -> u8 { self.clone() as u8 } } #[rustfmt::skip] #[derive(Clone)] pub enum IntFlag { VBlank = 0b0000, LCDStat = 0b0001, Timer = 0b0010, Serial = 0b0011, Joypad = 0b0100, } pub struct IntReg { pub data: u8, } impl IntReg { pub fn new() -> Self { Self { data: 0x00 } } pub fn req(&mut self, flag: IntFlag) { self.data |= 1 << flag as u8; } }
pub fn reverse_flag(&mut self, flag: Flag) { if self.is_flag_set(flag.clone()) { self.unset_flag(flag); } else { self.set_flag(flag); } }
function_block-full_function
[ { "content": "#[inline]\n\npub fn test_bit(v: u8, b: u8) -> bool {\n\n assert!(b <= 7);\n\n v & (1 << b) != 0\n\n}\n\n\n\n/// modify the bit to 0.\n", "file_path": "src/gameboy/util.rs", "rank": 0, "score": 184909.29057740478 }, { "content": "#[inline]\n\npub fn clear_bit(v: u8, b: u8)...
Rust
contracts/tland-token/src/msg.rs
highwayns/realestate
508db9bc5578ae57050e9bd9e0faacd4f5746cf6
use cosmwasm_std::{StdError, StdResult, Uint128, Binary}; use cw20::{Cw20Coin, Logo}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cw0::Expiration; #[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq)] pub struct InstantiateMarketingInfo { pub project: Option<String>, pub description: Option<String>, pub marketing: Option<String>, pub logo: Option<Logo>, } #[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq)] pub struct InstantiateMsg { pub owner: String, pub name: String, pub symbol: String, pub decimals: u8, pub initial_balances: Vec<Cw20Coin>, pub marketing: Option<InstantiateMarketingInfo>, } impl InstantiateMsg { pub fn validate(&self) -> StdResult<()> { if !is_valid_name(&self.name) { return Err(StdError::generic_err( "Name is not in the expected format (3-50 UTF-8 bytes)", )); } if !is_valid_symbol(&self.symbol) { return Err(StdError::generic_err( "Ticker symbol is not in expected format [a-zA-Z\\-]{3,12}", )); } if self.decimals > 18 { return Err(StdError::generic_err("Decimals must not exceed 18")); } Ok(()) } } fn is_valid_name(name: &str) -> bool { let bytes = name.as_bytes(); if bytes.len() < 3 || bytes.len() > 50 { return false; } true } fn is_valid_symbol(symbol: &str) -> bool { let bytes = symbol.as_bytes(); if bytes.len() < 3 || bytes.len() > 12 { return false; } for byte in bytes.iter() { if (*byte != 45) && (*byte < 65 || *byte > 90) && (*byte < 97 || *byte > 122) { return false; } } true } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum QueryMsg { Config {}, Balance { address: String }, TokenInfo {}, Allowance { owner: String, spender: String }, AllAllowances { owner: String, start_after: Option<String>, limit: Option<u32>, }, AllAccounts { start_after: Option<String>, limit: Option<u32>, }, MarketingInfo {}, DownloadLogo {}, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct MigrateMsg {} #[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)] #[serde(rename_all = "snake_case")] pub enum ExecuteMsg { UpdateConfig { owner: Option<String>, }, Transfer { recipient: String, amount: Uint128 }, Burn { amount: Uint128 }, Send { contract: String, amount: Uint128, msg: Binary, }, IncreaseAllowance { spender: String, amount: Uint128, expires: Option<Expiration>, }, DecreaseAllowance { spender: String, amount: Uint128, expires: Option<Expiration>, }, TransferFrom { owner: String, recipient: String, amount: Uint128, }, SendFrom { owner: String, contract: String, amount: Uint128, msg: Binary, }, BurnFrom { owner: String, amount: Uint128 }, UpdateMarketing { project: Option<String>, description: Option<String>, marketing: Option<String>, }, UploadLogo(Logo), WithdrawLockedFunds { denom: String, amount: Uint128, recipient: String, } }
use cosmwasm_std::{StdError, StdResult, Uint128, Binary}; use cw20::{Cw20Coin, Logo}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cw0::Expiration; #[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq)] pub struct InstantiateMarketingInfo { pub project: Option<String>, pub description: Option<String>, pub marketing: Option<String>, pub logo: Option<Logo>, } #[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq)] pub struct InstantiateMsg { pub owner: String, pub name: String, pub symbol: String, pub decimals: u8, pub initial_balances: Vec<Cw20Coin>, pub marketing: Option<InstantiateMarketingInfo>, } impl InstantiateMsg { pub fn validate(&self) -> StdResult<()> { if !is_valid_name(&self.name) { return Err(StdError::generic_err( "Name is not in the expected format (3-50 UTF-8 bytes)", )); } if !i
} fn is_valid_name(name: &str) -> bool { let bytes = name.as_bytes(); if bytes.len() < 3 || bytes.len() > 50 { return false; } true } fn is_valid_symbol(symbol: &str) -> bool { let bytes = symbol.as_bytes(); if bytes.len() < 3 || bytes.len() > 12 { return false; } for byte in bytes.iter() { if (*byte != 45) && (*byte < 65 || *byte > 90) && (*byte < 97 || *byte > 122) { return false; } } true } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum QueryMsg { Config {}, Balance { address: String }, TokenInfo {}, Allowance { owner: String, spender: String }, AllAllowances { owner: String, start_after: Option<String>, limit: Option<u32>, }, AllAccounts { start_after: Option<String>, limit: Option<u32>, }, MarketingInfo {}, DownloadLogo {}, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct MigrateMsg {} #[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)] #[serde(rename_all = "snake_case")] pub enum ExecuteMsg { UpdateConfig { owner: Option<String>, }, Transfer { recipient: String, amount: Uint128 }, Burn { amount: Uint128 }, Send { contract: String, amount: Uint128, msg: Binary, }, IncreaseAllowance { spender: String, amount: Uint128, expires: Option<Expiration>, }, DecreaseAllowance { spender: String, amount: Uint128, expires: Option<Expiration>, }, TransferFrom { owner: String, recipient: String, amount: Uint128, }, SendFrom { owner: String, contract: String, amount: Uint128, msg: Binary, }, BurnFrom { owner: String, amount: Uint128 }, UpdateMarketing { project: Option<String>, description: Option<String>, marketing: Option<String>, }, UploadLogo(Logo), WithdrawLockedFunds { denom: String, amount: Uint128, recipient: String, } }
s_valid_symbol(&self.symbol) { return Err(StdError::generic_err( "Ticker symbol is not in expected format [a-zA-Z\\-]{3,12}", )); } if self.decimals > 18 { return Err(StdError::generic_err("Decimals must not exceed 18")); } Ok(()) }
function_block-function_prefixed
[ { "content": "pub fn query_allowance(deps: Deps, owner: String, spender: String) -> StdResult<AllowanceResponse> {\n\n let owner_addr = deps.api.addr_validate(&owner)?;\n\n let spender_addr = deps.api.addr_validate(&spender)?;\n\n let allowance = ALLOWANCES\n\n .may_load(deps.storage, (&owner_ad...
Rust
07-rust/stm32l0x1/stm32l0x1_pac/src/syscfg_comp/comp1_ctrl.rs
aaronhktan/stm32-exploration
dcd7674424cd17b02b85c6b3ce533456d5037d65
#[doc = "Reader of register COMP1_CTRL"] pub type R = crate::R<u32, super::COMP1_CTRL>; #[doc = "Writer for register COMP1_CTRL"] pub type W = crate::W<u32, super::COMP1_CTRL>; #[doc = "Register COMP1_CTRL `reset()`'s with value 0"] impl crate::ResetValue for super::COMP1_CTRL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `COMP1EN`"] pub type COMP1EN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `COMP1EN`"] pub struct COMP1EN_W<'a> { w: &'a mut W, } impl<'a> COMP1EN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `COMP1INNSEL`"] pub type COMP1INNSEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `COMP1INNSEL`"] pub struct COMP1INNSEL_W<'a> { w: &'a mut W, } impl<'a> COMP1INNSEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 4)) | (((value as u32) & 0x03) << 4); self.w } } #[doc = "Reader of field `COMP1WM`"] pub type COMP1WM_R = crate::R<bool, bool>; #[doc = "Write proxy for field `COMP1WM`"] pub struct COMP1WM_W<'a> { w: &'a mut W, } impl<'a> COMP1WM_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Reader of field `COMP1LPTIMIN1`"] pub type COMP1LPTIMIN1_R = crate::R<bool, bool>; #[doc = "Write proxy for field `COMP1LPTIMIN1`"] pub struct COMP1LPTIMIN1_W<'a> { w: &'a mut W, } impl<'a> COMP1LPTIMIN1_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "Reader of field `COMP1POLARITY`"] pub type COMP1POLARITY_R = crate::R<bool, bool>; #[doc = "Write proxy for field `COMP1POLARITY`"] pub struct COMP1POLARITY_W<'a> { w: &'a mut W, } impl<'a> COMP1POLARITY_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "Reader of field `COMP1VALUE`"] pub type COMP1VALUE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `COMP1VALUE`"] pub struct COMP1VALUE_W<'a> { w: &'a mut W, } impl<'a> COMP1VALUE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 30)) | (((value as u32) & 0x01) << 30); self.w } } #[doc = "Reader of field `COMP1LOCK`"] pub type COMP1LOCK_R = crate::R<bool, bool>; #[doc = "Write proxy for field `COMP1LOCK`"] pub struct COMP1LOCK_W<'a> { w: &'a mut W, } impl<'a> COMP1LOCK_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31); self.w } } impl R { #[doc = "Bit 0 - Comparator 1 enable bit"] #[inline(always)] pub fn comp1en(&self) -> COMP1EN_R { COMP1EN_R::new((self.bits & 0x01) != 0) } #[doc = "Bits 4:5 - Comparator 1 Input Minus connection configuration bit"] #[inline(always)] pub fn comp1innsel(&self) -> COMP1INNSEL_R { COMP1INNSEL_R::new(((self.bits >> 4) & 0x03) as u8) } #[doc = "Bit 8 - Comparator 1 window mode selection bit"] #[inline(always)] pub fn comp1wm(&self) -> COMP1WM_R { COMP1WM_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 12 - Comparator 1 LPTIM input propagation bit"] #[inline(always)] pub fn comp1lptimin1(&self) -> COMP1LPTIMIN1_R { COMP1LPTIMIN1_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 15 - Comparator 1 polarity selection bit"] #[inline(always)] pub fn comp1polarity(&self) -> COMP1POLARITY_R { COMP1POLARITY_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 30 - Comparator 1 output status bit"] #[inline(always)] pub fn comp1value(&self) -> COMP1VALUE_R { COMP1VALUE_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 31 - COMP1_CSR register lock bit"] #[inline(always)] pub fn comp1lock(&self) -> COMP1LOCK_R { COMP1LOCK_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Comparator 1 enable bit"] #[inline(always)] pub fn comp1en(&mut self) -> COMP1EN_W { COMP1EN_W { w: self } } #[doc = "Bits 4:5 - Comparator 1 Input Minus connection configuration bit"] #[inline(always)] pub fn comp1innsel(&mut self) -> COMP1INNSEL_W { COMP1INNSEL_W { w: self } } #[doc = "Bit 8 - Comparator 1 window mode selection bit"] #[inline(always)] pub fn comp1wm(&mut self) -> COMP1WM_W { COMP1WM_W { w: self } } #[doc = "Bit 12 - Comparator 1 LPTIM input propagation bit"] #[inline(always)] pub fn comp1lptimin1(&mut self) -> COMP1LPTIMIN1_W { COMP1LPTIMIN1_W { w: self } } #[doc = "Bit 15 - Comparator 1 polarity selection bit"] #[inline(always)] pub fn comp1polarity(&mut self) -> COMP1POLARITY_W { COMP1POLARITY_W { w: self } } #[doc = "Bit 30 - Comparator 1 output status bit"] #[inline(always)] pub fn comp1value(&mut self) -> COMP1VALUE_W { COMP1VALUE_W { w: self } } #[doc = "Bit 31 - COMP1_CSR register lock bit"] #[inline(always)] pub fn comp1lock(&mut self) -> COMP1LOCK_W { COMP1LOCK_W { w: self } } }
#[doc = "Reader of register COMP1_CTRL"] pub type R = crate::R<u32, super::COMP1_CTRL>; #[doc = "Writer for register COMP1_CTRL"] pub type W = crate::W<u32, super::COMP1_CTRL>; #[doc = "Register COMP1_CTRL `reset()`'s with value 0"] impl crate::ResetValue for super::COMP1_CTRL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `COMP1EN`"] pub type COMP1EN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `COMP1EN`"] pub struct COMP1EN_W<'a> { w: &'a mut W, } impl<'a> COMP1EN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `COMP1INNSEL`"] pub type COMP1INNSEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `COMP1INNSEL`"] pub struct COMP1INNSEL_W<'a> { w: &'a mut W, } impl<'a> COMP1INNSEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 4)) | (((value as u32) & 0x03) << 4); self.w } } #[doc = "Reader of field `COMP1WM`"] pub type COMP1WM_R = crate::R<bool, bool>; #[doc = "Write proxy for field `COMP1WM`"] pub struct COMP1WM_W<'a> { w: &'a mut W, } impl<'a> COMP1WM_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Reader of field `COMP1LPTIMIN1`"] pub type COMP1LPTIMIN1_R = crate::R<bool, bool>; #[doc = "Write proxy for field `COMP1LPTIMIN1`"] pub struct COMP1LPTIMIN1_W<'a> { w: &'a mut W, } impl<'a> COMP1LPTIMIN1_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "Reader of field `COMP1POLARITY`"] pub type COMP1POLARITY_R = crate::R<bool, bool>; #[doc = "Write proxy for field `COMP1POLARITY`"] pub struct COMP1POLARITY_W<'a> { w: &'a mut W, } impl<'a> COMP1POLARITY_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "Reader of field `COMP1VALUE`"] pub type COMP1VALUE_R = crate::R<bool, bool>; #[doc
TY_R { COMP1POLARITY_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 30 - Comparator 1 output status bit"] #[inline(always)] pub fn comp1value(&self) -> COMP1VALUE_R { COMP1VALUE_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 31 - COMP1_CSR register lock bit"] #[inline(always)] pub fn comp1lock(&self) -> COMP1LOCK_R { COMP1LOCK_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Comparator 1 enable bit"] #[inline(always)] pub fn comp1en(&mut self) -> COMP1EN_W { COMP1EN_W { w: self } } #[doc = "Bits 4:5 - Comparator 1 Input Minus connection configuration bit"] #[inline(always)] pub fn comp1innsel(&mut self) -> COMP1INNSEL_W { COMP1INNSEL_W { w: self } } #[doc = "Bit 8 - Comparator 1 window mode selection bit"] #[inline(always)] pub fn comp1wm(&mut self) -> COMP1WM_W { COMP1WM_W { w: self } } #[doc = "Bit 12 - Comparator 1 LPTIM input propagation bit"] #[inline(always)] pub fn comp1lptimin1(&mut self) -> COMP1LPTIMIN1_W { COMP1LPTIMIN1_W { w: self } } #[doc = "Bit 15 - Comparator 1 polarity selection bit"] #[inline(always)] pub fn comp1polarity(&mut self) -> COMP1POLARITY_W { COMP1POLARITY_W { w: self } } #[doc = "Bit 30 - Comparator 1 output status bit"] #[inline(always)] pub fn comp1value(&mut self) -> COMP1VALUE_W { COMP1VALUE_W { w: self } } #[doc = "Bit 31 - COMP1_CSR register lock bit"] #[inline(always)] pub fn comp1lock(&mut self) -> COMP1LOCK_W { COMP1LOCK_W { w: self } } }
= "Write proxy for field `COMP1VALUE`"] pub struct COMP1VALUE_W<'a> { w: &'a mut W, } impl<'a> COMP1VALUE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 30)) | (((value as u32) & 0x01) << 30); self.w } } #[doc = "Reader of field `COMP1LOCK`"] pub type COMP1LOCK_R = crate::R<bool, bool>; #[doc = "Write proxy for field `COMP1LOCK`"] pub struct COMP1LOCK_W<'a> { w: &'a mut W, } impl<'a> COMP1LOCK_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31); self.w } } impl R { #[doc = "Bit 0 - Comparator 1 enable bit"] #[inline(always)] pub fn comp1en(&self) -> COMP1EN_R { COMP1EN_R::new((self.bits & 0x01) != 0) } #[doc = "Bits 4:5 - Comparator 1 Input Minus connection configuration bit"] #[inline(always)] pub fn comp1innsel(&self) -> COMP1INNSEL_R { COMP1INNSEL_R::new(((self.bits >> 4) & 0x03) as u8) } #[doc = "Bit 8 - Comparator 1 window mode selection bit"] #[inline(always)] pub fn comp1wm(&self) -> COMP1WM_R { COMP1WM_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 12 - Comparator 1 LPTIM input propagation bit"] #[inline(always)] pub fn comp1lptimin1(&self) -> COMP1LPTIMIN1_R { COMP1LPTIMIN1_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 15 - Comparator 1 polarity selection bit"] #[inline(always)] pub fn comp1polarity(&self) -> COMP1POLARI
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
riscv/src/mmu.rs
plorefice/rv6
adb7e28994b08b86596d2bdfbfee0ca5832e3d21
use core::{ fmt, slice::{Iter, IterMut}, }; use bitflags::bitflags; use kmm::{allocator::FrameAllocator, Align}; use crate::{ addr::{PAGE_SHIFT, PAGE_SIZE}, PhysAddr, VirtAddr, }; #[cfg(feature = "sv39")] const PTE_PPN_MASK: u64 = 0x3ff_ffff; #[cfg(feature = "sv48")] const PTE_PPN_MASK: u64 = 0xfff_ffff_ffff; const PTE_PPN_OFFSET: u64 = 10; #[cfg(feature = "sv39")] const PAGE_LEVELS: usize = 3; #[cfg(feature = "sv48")] const PAGE_LEVELS: usize = 4; bitflags! { pub struct EntryFlags: u64 { const VALID = 1 << 0; const READ = 1 << 1; const WRITE = 1 << 2; const EXEC = 1 << 3; const USER = 1 << 4; const GLOBAL = 1 << 5; const ACCESS = 1 << 6; const DIRTY = 1 << 7; const RW = Self::READ.bits | Self::WRITE.bits; const RX = Self::READ.bits | Self::EXEC.bits; const RWX = Self::READ.bits | Self::WRITE.bits | Self::EXEC.bits; const RWXUG = Self::RWX.bits | Self::USER.bits | Self::GLOBAL.bits; const ALL = 0xf; } } #[derive(Debug)] pub struct PageTable { entries: [Entry; 512], } impl PageTable { pub fn clear(&mut self) { for entry in &mut self.entries { entry.clear(); } } pub fn get_entry(&self, i: usize) -> Option<&Entry> { self.entries.get(i) } pub fn get_entry_mut(&mut self, i: usize) -> Option<&mut Entry> { self.entries.get_mut(i) } pub fn iter(&self) -> Iter<'_, Entry> { self.entries.iter() } pub fn iter_mut(&mut self) -> IterMut<'_, Entry> { self.entries.iter_mut() } } impl fmt::Display for PageTable { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for (i, e) in self.entries.iter().enumerate() { if e.is_valid() { writeln!(f, "{:>3}: {}", i, e)?; } } Ok(()) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct Entry { inner: EntryFlags, } impl Entry { pub fn is_valid(&self) -> bool { self.inner.contains(EntryFlags::VALID) } pub fn is_read(&self) -> bool { self.inner.contains(EntryFlags::READ) } pub fn is_write(&self) -> bool { self.inner.contains(EntryFlags::WRITE) } pub fn is_exec(&self) -> bool { self.inner.contains(EntryFlags::EXEC) } pub fn is_user(&self) -> bool { self.inner.contains(EntryFlags::USER) } pub fn is_global(&self) -> bool { self.inner.contains(EntryFlags::GLOBAL) } pub fn is_accessed(&self) -> bool { self.inner.contains(EntryFlags::ACCESS) } pub fn is_dirty(&self) -> bool { self.inner.contains(EntryFlags::DIRTY) } pub fn is_leaf(&self) -> bool { self.inner .intersects(EntryFlags::READ | EntryFlags::WRITE | EntryFlags::EXEC) } pub fn flags(&self) -> EntryFlags { self.inner & EntryFlags::ALL } pub fn clear(&mut self) { self.inner.bits = 0; } pub fn set_flags(&mut self, flags: EntryFlags) { self.inner &= !EntryFlags::ALL; self.inner |= flags; } pub fn get_ppn(&self) -> u64 { (self.inner.bits() >> PTE_PPN_OFFSET) & PTE_PPN_MASK } pub fn set_ppn(&mut self, ppn: u64) { self.inner.bits &= !(PTE_PPN_MASK << PTE_PPN_OFFSET); self.inner.bits |= (ppn & PTE_PPN_MASK) << PTE_PPN_OFFSET; } } impl fmt::Display for Entry { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "phy: 0x{:016x} ", self.get_ppn() << PTE_PPN_OFFSET)?; write!( f, "{} {} {} {} {} {} {}", if self.is_read() { 'R' } else { ' ' }, if self.is_write() { 'W' } else { ' ' }, if self.is_exec() { 'X' } else { ' ' }, if self.is_user() { 'U' } else { ' ' }, if self.is_global() { 'G' } else { ' ' }, if self.is_accessed() { 'A' } else { ' ' }, if self.is_dirty() { 'D' } else { ' ' }, ) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum PageSize { Kb, Mb, Gb, #[cfg(feature = "sv48")] Tb, } impl PageSize { fn to_table_level(self) -> usize { match self { PageSize::Kb => 0, PageSize::Mb => 1, PageSize::Gb => 2, #[cfg(feature = "sv48")] PageSize::Tb => 3, } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum MapError { AlreadyMapped, AllocationFailed, } #[derive(Debug)] pub struct OffsetPageMapper<'a> { rpt: &'a mut PageTable, phys_offset: VirtAddr, } impl<'a> OffsetPageMapper<'a> { pub unsafe fn new(rpt: &'a mut PageTable, phys_offset: VirtAddr) -> Self { Self { rpt, phys_offset } } pub unsafe fn map<A>( &mut self, vaddr: VirtAddr, paddr: PhysAddr, page_size: PageSize, mut flags: EntryFlags, frame_allocator: &mut A, ) -> Result<(), MapError> where A: FrameAllocator<PhysAddr, PAGE_SIZE>, { #[cfg(feature = "sv39")] let vpn = [vaddr.vpn0(), vaddr.vpn1(), vaddr.vpn2()]; #[cfg(feature = "sv48")] let vpn = [vaddr.vpn0(), vaddr.vpn1(), vaddr.vpn2(), vaddr.vpn3()]; let mut pte = self.rpt.get_entry_mut(vpn[PAGE_LEVELS - 1]).unwrap(); for i in (page_size.to_table_level()..PAGE_LEVELS - 1).rev() { let table_paddr = if !pte.is_valid() { let new_table_addr = unsafe { frame_allocator.alloc(1) }.ok_or(MapError::AllocationFailed)?; pte.clear(); pte.set_flags(EntryFlags::VALID); pte.set_ppn(new_table_addr.page_index()); new_table_addr } else { PhysAddr::new(pte.get_ppn() << PAGE_SHIFT) }; let table = unsafe { self.phys_to_virt(table_paddr) .as_mut_ptr::<PageTable>() .as_mut() .unwrap() }; pte = table.get_entry_mut(vpn[i]).unwrap(); } flags &= EntryFlags::RWXUG; if pte.is_valid() && pte.flags() & EntryFlags::RWXUG != flags { return Err(MapError::AlreadyMapped); } pte.set_flags(flags | EntryFlags::VALID); pte.set_ppn(paddr.page_index()); Ok(()) } pub unsafe fn identity_map_range<A>( &mut self, start: PhysAddr, end: PhysAddr, flags: EntryFlags, frame_allocator: &mut A, ) -> Result<(), MapError> where A: FrameAllocator<PhysAddr, PAGE_SIZE>, { let start = start.align_down(PAGE_SIZE); let end = end.align_up(PAGE_SIZE); let num_pages = u64::from(end - start) >> PAGE_SHIFT; for i in 0..num_pages { let addr = start + (i << PAGE_SHIFT); unsafe { self.map( VirtAddr::new(u64::from(addr) as usize), addr, PageSize::Kb, flags, frame_allocator, )?; } } Ok(()) } pub fn phys_to_virt(&self, paddr: PhysAddr) -> VirtAddr { VirtAddr::new(paddr.data() as usize) + self.phys_offset } pub fn virt_to_phys(&self, vaddr: VirtAddr) -> Option<PhysAddr> { #[cfg(feature = "sv39")] let vpn = [ (vaddr.data() >> 12) & 0x1ff, (vaddr.data() >> 21) & 0x1ff, (vaddr.data() >> 30) & 0x1ff, ]; #[cfg(feature = "sv48")] let vpn = [ (vaddr.data() >> 12) & 0x1ff, (vaddr.data() >> 21) & 0x1ff, (vaddr.data() >> 30) & 0x1ff, (vaddr.data() >> 39) & 0x1ff, ]; let mut table = &*self.rpt; for i in (0..PAGE_LEVELS).rev() { let pte = table.get_entry(vpn[i]).unwrap(); if !pte.is_valid() { break; } if pte.is_leaf() { let mut ppn = pte.get_ppn(); for (lvl, vpn) in vpn.iter().enumerate().take(i) { ppn |= (vpn << (lvl * 9)) as u64; } return Some(PhysAddr::new(ppn << PAGE_SHIFT) + vaddr.page_offset() as u64); } table = unsafe { self.phys_to_virt(PhysAddr::from_ppn(pte.get_ppn())) .as_ptr::<PageTable>() .as_ref() .unwrap() }; } None } }
use core::{ fmt, slice::{Iter, IterMut}, }; use bitflags::bitflags; use kmm::{allocator::FrameAllocator, Align}; use crate::{ addr::{PAGE_SHIFT, PAGE_SIZE}, PhysAddr, VirtAddr, }; #[cfg(feature = "sv39")] const PTE_PPN_MASK: u64 = 0x3ff_ffff; #[cfg(feature = "sv48")] const PTE_PPN_MASK: u64 = 0xfff_ffff_ffff; const PTE_PPN_OFFSET: u64 = 10; #[cfg(feature = "sv39")] const PAGE_LEVELS: usize = 3; #[cfg(feature = "sv48")] const PAGE_LEVELS: usize = 4; bitflags! { pub struct EntryFlags: u64 { const VALID = 1 << 0; const READ = 1 << 1; const WRITE = 1 << 2; const EXEC = 1 << 3; const USER = 1 << 4; const GLOBAL = 1 << 5; const ACCESS = 1 << 6; const DIRTY = 1 << 7; const RW = Self::READ.bits | Self::WRITE.bits; const RX = Self::READ.bits | Self::EXEC.bits; const RWX = Self::READ.bits | Self::WRITE.bits | Self::EXEC.bits; const RWXUG = Self::RWX.bits | Self::USER.bits | Self::GLOBAL.bits; const ALL = 0xf; } } #[derive(Debug)] pub struct PageTable { entries: [Entry; 512], } impl PageTable { pub fn clear(&mut self) { for entry in &mut self.entries { entry.clear(); } } pub fn get_entry(&self, i: usize) -> Option<&Entry> { self.entries.get(i) } pub fn get_entry_mut(&mut self, i: usize) -> Option<&mut Entry> { self.entries.get_mut(i) } pub fn iter(&self) -> Iter<'_, Entry> { self.entries.iter() } pub fn iter_mut(&mut self) -> IterMut<'_, Entry> { self.entries.iter_mut() } } impl fmt::Display for PageTable { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for (i, e) in self.entries.iter().enumerate() { if e.is_valid() { writeln!(f, "{:>3}: {}", i, e)?; } } Ok(()) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct Entry { inner: EntryFlags, } impl Entry { pub fn is_valid(&self) -> bool { self.inner.contains(EntryFlags::VALID) } pub fn is_read(&self) -> bool { self.inner.contains(EntryFlags::READ) } pub fn is_write(&self) -> bool { self.inner.contains(EntryFlags::WRITE) } pub fn is_exec(&self) -> bool { self.inner.contains(EntryFlags::EXEC) } pub fn is_user(&self) -> bool { self.inner.contains(EntryFlags::USER) } pub fn is_global(&self) -> bool { self.inner.contains(EntryFlags::GLOBAL) } pub fn is_accessed(&self) -> bool { self.inner.contains(EntryFlags::ACCESS) } pub fn is_dirty(&self) -> bool { self.inner.contains(EntryFlags::DIRTY) } pub fn is_leaf(&self) -> bool { self.inner .intersects(EntryFlags::READ | EntryFlags::WRITE | EntryFlags::EXEC) } pub fn flags(&self) -> EntryFlags { self.inner & EntryFlags::ALL } pub fn clear(&mut self) { self.inner.bits = 0; } pub fn set_flags(&mut self, flags: EntryFlags) { self.inner &= !EntryFlags::ALL; self.inner |= flags; } pub fn get_ppn(&self) -> u64 { (self.inner.bits() >> PTE_PPN_OFFSET) & PTE_PPN_MASK } pub fn set_ppn(&mut self, ppn: u64) { self.inner.bits &= !(PTE_PPN_MASK << PTE_PPN_OFFSET); self.inner.bits |= (ppn & PTE_PPN_MASK) << PTE_PPN_OFFSET; } } impl fmt::Display for Entry { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "phy: 0x{:016x} ", self.get_ppn() << PTE_PPN_OFFSET)?; write!( f, "{} {} {} {} {} {} {}", if self.is_read() { 'R' } else { ' ' }, if self.is_write() { 'W' } else { ' ' }, if self.is_exec() { 'X' } else { ' ' }, if self.is_user() { 'U' } else { ' ' }, if self.is_global() { 'G' } else { ' ' }, if self.is_accessed() { 'A' } else { ' ' }, if self.is_dirty() { 'D' } else { ' ' }, ) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum PageSize { Kb, Mb, Gb, #[cfg(feature = "sv48")] Tb, } impl PageSize { fn to_table_level(self) -> usize { match self { PageSize::Kb => 0, PageSize::Mb => 1, PageSize::Gb => 2, #[cfg(feature = "sv48")] PageSize::Tb => 3, } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum MapError { AlreadyMapped, AllocationFailed, } #[derive(Debug)] pub struct OffsetPageMapper<'a> { rpt: &'a mut PageTable, phys_offset: VirtAddr, } impl<'a> OffsetPageMapper<'a> { pub unsafe fn new(rpt: &'a mut PageTable, phys_offset: VirtAddr) -> Self { Self { rpt, phys_offset } } pub unsafe fn map<A>( &mut self, vaddr: VirtAddr, paddr: PhysAddr, page_size: PageSize, mut flags: EntryFlags, frame_allocator: &mut A, ) -> Result<(), MapError> where A: FrameAllocator<PhysAddr, PAGE_SIZE>, { #[cfg(feature = "sv39")] let vpn = [vaddr.vpn0(), vaddr.vpn1(), vaddr.vpn2()]; #[cfg(feature = "sv48")] let vpn = [vaddr.vpn0(), vaddr.vpn1(), vaddr.vpn2(), vaddr.vpn3()]; let mut pte = self.rpt.get_entry_mut(vpn[PAGE_LEVELS - 1]).unwrap(); for i in (page_size.to_table_level()..PAGE_LEVELS - 1).rev() { let table_paddr = if !pte.is_valid() { let new_table_addr = unsafe { frame_allocator.alloc(1) }.ok_or(MapError::AllocationFailed)?; pte.clear(); pte.set_flags(EntryFlags::VALID); pte.set_ppn(new_table_addr.page_index()); new_table_addr } else { PhysAddr::new(pte.get_ppn() << PAGE_SHIFT) }; let table = unsafe { self.phys_to_virt(table_paddr) .as_mut_ptr::<PageTable>() .as_mut() .unwrap() }; pte = table.get_entry_mut(vpn[i]).unwrap(); } flags &= EntryFlags::RWXUG; if pte.is_valid() && pte.flags() & EntryFlags::RWXUG != flags { return Err(MapError::AlreadyMappe
pub unsafe fn identity_map_range<A>( &mut self, start: PhysAddr, end: PhysAddr, flags: EntryFlags, frame_allocator: &mut A, ) -> Result<(), MapError> where A: FrameAllocator<PhysAddr, PAGE_SIZE>, { let start = start.align_down(PAGE_SIZE); let end = end.align_up(PAGE_SIZE); let num_pages = u64::from(end - start) >> PAGE_SHIFT; for i in 0..num_pages { let addr = start + (i << PAGE_SHIFT); unsafe { self.map( VirtAddr::new(u64::from(addr) as usize), addr, PageSize::Kb, flags, frame_allocator, )?; } } Ok(()) } pub fn phys_to_virt(&self, paddr: PhysAddr) -> VirtAddr { VirtAddr::new(paddr.data() as usize) + self.phys_offset } pub fn virt_to_phys(&self, vaddr: VirtAddr) -> Option<PhysAddr> { #[cfg(feature = "sv39")] let vpn = [ (vaddr.data() >> 12) & 0x1ff, (vaddr.data() >> 21) & 0x1ff, (vaddr.data() >> 30) & 0x1ff, ]; #[cfg(feature = "sv48")] let vpn = [ (vaddr.data() >> 12) & 0x1ff, (vaddr.data() >> 21) & 0x1ff, (vaddr.data() >> 30) & 0x1ff, (vaddr.data() >> 39) & 0x1ff, ]; let mut table = &*self.rpt; for i in (0..PAGE_LEVELS).rev() { let pte = table.get_entry(vpn[i]).unwrap(); if !pte.is_valid() { break; } if pte.is_leaf() { let mut ppn = pte.get_ppn(); for (lvl, vpn) in vpn.iter().enumerate().take(i) { ppn |= (vpn << (lvl * 9)) as u64; } return Some(PhysAddr::new(ppn << PAGE_SHIFT) + vaddr.page_offset() as u64); } table = unsafe { self.phys_to_virt(PhysAddr::from_ppn(pte.get_ppn())) .as_ptr::<PageTable>() .as_ref() .unwrap() }; } None } }
d); } pte.set_flags(flags | EntryFlags::VALID); pte.set_ppn(paddr.page_index()); Ok(()) }
function_block-function_prefixed
[ { "content": "/// A physical memory address representable as an integer of type `U`.\n\npub trait PhysicalAddress<U>: Copy + Clone + Into<U> + AddressOps<U> {}\n\n\n", "file_path": "kmm/src/lib.rs", "rank": 0, "score": 142634.8631566231 }, { "content": "/// A trait for numeric types that can...
Rust
src/bin/test_merge.rs
GuilloteauQ/rayon-adaptive
ad3c82ca5d942df9c052b079e20d0331f840e303
use itertools::{iproduct, Itertools}; use rand::Rng; use rayon_adaptive::adaptive_sort_raw_with_policies_swap_blocks; use rayon_adaptive::Policy; use std::fs::File; use std::io::prelude::*; use std::iter::{once, repeat_with}; use thread_binder::ThreadPoolBuilder; use time::precise_time_ns; fn random_vec_with_range(size: usize, min_value: u32, max_value: u32) -> Vec<u32> { (0..size) .map(|_| rand::thread_rng().gen_range(min_value, max_value)) .collect() } fn sorted_vec(size: usize) -> Vec<u32> { (0..size).map(|x| x as u32).collect() } fn reversed_vec(size: usize) -> Vec<u32> { (0..size).rev().map(|x| x as u32).collect() } fn half_sorted(size: usize) -> Vec<u32> { let mid = size / 2; (0..mid).rev().chain(mid..size).map(|x| x as u32).collect() } fn random_vec_with_duplicates(size: usize) -> Vec<u32> { random_vec_with_range(size, 0, size as u32 / 8) } fn random_vec(size: usize) -> Vec<u32> { random_vec_with_range(size, 0, size as u32) } fn bench<INPUT, I, F>(init_fn: I, timed_fn: F) -> (u64, bool) where INPUT: Sized, I: Fn() -> INPUT, F: Fn(INPUT) -> bool, { let input = init_fn(); let begin_time: u64 = precise_time_ns(); let state = timed_fn(input); let end_time: u64 = precise_time_ns(); (end_time - begin_time, state) } fn tuple_to_vec<A: Clone, B: Clone>(v: &Vec<(A, B)>) -> (Vec<A>, Vec<B>) { let mut va = Vec::new(); let mut vb = Vec::new(); for (a, b) in v.iter() { va.push(a.clone()); vb.push(b.clone()); } (va, vb) } fn average_times<INPUT: Sized, I: Fn() -> INPUT, F: Fn(INPUT) -> bool>( init_fn: I, timed_fn: F, iterations: usize, ) -> (f64, usize) { let mut ve = Vec::new(); for _ in 0..iterations { ve.push(bench(&init_fn, &timed_fn)); } let v = tuple_to_vec(&ve); let time: f64 = v.0.iter().sum::<u64>() as f64 / iterations as f64; let states: usize = v.1.iter().map(|&b| if b { 1 } else { 0 }).sum(); (time, states) } fn times_by_processors< INPUT: Sized, I: Fn() -> INPUT + Send + Copy + Sync, F: Fn(INPUT) -> bool + Send + Copy + Sync, THREADS: IntoIterator<Item = usize>, >( init_fn: I, timed_fn: F, iterations: usize, threads_numbers: THREADS, ) -> Vec<(f64, usize)> { threads_numbers .into_iter() .map(move |threads| { let pool = ThreadPoolBuilder::new() .num_threads(threads) .build() .expect("building pool failed"); pool.install(|| average_times(init_fn, timed_fn, iterations)) }) .collect() } fn main() { let iterations = 100; let sizes = vec![1_000_000]; let threads: Vec<usize> = vec![4]; let policies = vec![Policy::Join(1000), Policy::JoinContext(1000)]; let input_generators = vec![ /* ( Box::new(random_vec) as Box<Fn(usize) -> Vec<u32> + Sync>, "random", ), */ ( Box::new(sorted_vec) as Box<Fn(usize) -> Vec<u32> + Sync>, "sorted", ), /* ( Box::new(reversed_vec) as Box<Fn(usize) -> Vec<u32> + Sync>, "reversed", ), ( Box::new(random_vec_with_duplicates) as Box<Fn(usize) -> Vec<u32> + Sync>, "random_with_duplicates", ), ( Box::new(half_sorted) as Box<Fn(usize) -> Vec<u32> + Sync>, "half sorted, half reversed", ), */ ]; let algorithms: Vec<_> = iproduct!(policies.clone(), policies.clone()) .map(|(sort_policy, fuse_policy)| { ( Box::new(move |mut v: Vec<u32>| { adaptive_sort_raw_with_policies_swap_blocks(&mut v, sort_policy, fuse_policy) }) as Box<Fn(Vec<u32>) -> bool + Sync + Send>, format!("Swap {:?}/{:?}", sort_policy, fuse_policy), ) }) .collect(); for (generator_f, generator_name) in input_generators.iter() { println!(">>> {}", generator_name); for size in sizes.iter() { println!("Size: {}", size); let algo_results: Vec<_> = algorithms .iter() .map(|(algo_f, name)| { print!("{}: ", name); let res = times_by_processors( || generator_f(*size), |v| algo_f(v), iterations, threads.clone(), ); print!( "{}/{} copies\n", res.iter().map(|(_, b)| b).sum::<usize>(), iterations ); res }) .collect(); } } }
use itertools::{iproduct, Itertools}; use rand::Rng; use rayon_adaptive::adaptive_sort_raw_with_policies_swap_blocks; use rayon_adaptive::Policy; use std::fs::File; use std::io::prelude::*; use std::iter::{once, repeat_with}; use thread_binder::ThreadPoolBuilder; use time::precise_time_ns; fn random_vec_with_range(size: usize, min_value: u32, max_value: u32) -> Vec<u32> { (0..size) .map(|_| rand::thread_rng().gen_range(min_value, max_value)) .collect() } fn sorted_vec(size: usize) -> Vec<u32> { (0..size).map(|x| x as u32).collect() } fn reversed_vec(size: usize) -> Vec<u32> { (0..size).rev().map(|x| x as u32).collect() } fn half_sorted(size: usize) -> Vec<u32> { let mid = size / 2; (0..mid).rev().chain(mid..size).map(|x| x as u32).collect() } fn random_vec_with_duplicates(size: usize) -> Vec<u32> { random_vec_with_range(size, 0, size as u32 / 8) } fn random_vec(size: usize) -> Vec<u32> { random_vec_with_range(size, 0, size as u32) } fn bench<INPUT, I, F>(init_fn: I, timed_fn: F) -> (u64, bool) where INPUT: Sized, I: Fn() -> INPUT, F: Fn(INPUT) -> bool, { let input = init_fn(); let begin_time: u64 = precise_time_ns(); let state = timed_fn(input); let end_time: u64 = precise_time_ns(); (end_time - begin_time, state) } fn tuple_to_vec<A: Clone, B: Clone>(v: &Vec<(A, B)>) -> (Vec<A>, Vec<B>) { let mut va = Vec::new(); let mut vb = Vec::new(); for (a, b) in v.iter() { va.push(a.clone()); vb.push(b.c
let sizes = vec![1_000_000]; let threads: Vec<usize> = vec![4]; let policies = vec![Policy::Join(1000), Policy::JoinContext(1000)]; let input_generators = vec![ /* ( Box::new(random_vec) as Box<Fn(usize) -> Vec<u32> + Sync>, "random", ), */ ( Box::new(sorted_vec) as Box<Fn(usize) -> Vec<u32> + Sync>, "sorted", ), /* ( Box::new(reversed_vec) as Box<Fn(usize) -> Vec<u32> + Sync>, "reversed", ), ( Box::new(random_vec_with_duplicates) as Box<Fn(usize) -> Vec<u32> + Sync>, "random_with_duplicates", ), ( Box::new(half_sorted) as Box<Fn(usize) -> Vec<u32> + Sync>, "half sorted, half reversed", ), */ ]; let algorithms: Vec<_> = iproduct!(policies.clone(), policies.clone()) .map(|(sort_policy, fuse_policy)| { ( Box::new(move |mut v: Vec<u32>| { adaptive_sort_raw_with_policies_swap_blocks(&mut v, sort_policy, fuse_policy) }) as Box<Fn(Vec<u32>) -> bool + Sync + Send>, format!("Swap {:?}/{:?}", sort_policy, fuse_policy), ) }) .collect(); for (generator_f, generator_name) in input_generators.iter() { println!(">>> {}", generator_name); for size in sizes.iter() { println!("Size: {}", size); let algo_results: Vec<_> = algorithms .iter() .map(|(algo_f, name)| { print!("{}: ", name); let res = times_by_processors( || generator_f(*size), |v| algo_f(v), iterations, threads.clone(), ); print!( "{}/{} copies\n", res.iter().map(|(_, b)| b).sum::<usize>(), iterations ); res }) .collect(); } } }
lone()); } (va, vb) } fn average_times<INPUT: Sized, I: Fn() -> INPUT, F: Fn(INPUT) -> bool>( init_fn: I, timed_fn: F, iterations: usize, ) -> (f64, usize) { let mut ve = Vec::new(); for _ in 0..iterations { ve.push(bench(&init_fn, &timed_fn)); } let v = tuple_to_vec(&ve); let time: f64 = v.0.iter().sum::<u64>() as f64 / iterations as f64; let states: usize = v.1.iter().map(|&b| if b { 1 } else { 0 }).sum(); (time, states) } fn times_by_processors< INPUT: Sized, I: Fn() -> INPUT + Send + Copy + Sync, F: Fn(INPUT) -> bool + Send + Copy + Sync, THREADS: IntoIterator<Item = usize>, >( init_fn: I, timed_fn: F, iterations: usize, threads_numbers: THREADS, ) -> Vec<(f64, usize)> { threads_numbers .into_iter() .map(move |threads| { let pool = ThreadPoolBuilder::new() .num_threads(threads) .build() .expect("building pool failed"); pool.install(|| average_times(init_fn, timed_fn, iterations)) }) .collect() } fn main() { let iterations = 100;
random
[ { "content": "/// compute a block size with the given function.\n\n/// this allows us to ensure we enforce important bounds on sizes.\n\nfn compute_size<F: Fn(usize) -> usize>(n: usize, sizing_function: F) -> usize {\n\n let p = current_num_threads();\n\n std::cmp::max(min(n / (2 * p), sizing_function(n))...
Rust
src/main.rs
igoyak/igrepper
6b5b66d4a6b45382d3e8f45571b111c5e0f4b9a4
extern crate clap; extern crate libc; use clap::{App, Arg}; use inotify::{Inotify, WatchMask}; use libc::close; use libc::open; use std::env; use crate::igrepper::igrepper; use file_reading::{SourceInput, SourceProducer}; mod file_reading; mod igrepper; const PARAMETER_ERROR: &str = "Data can only be passed by STDIN if no file parameter is specified"; const DEFAULT_EDITOR_COMMAND: [&str; 3] = ["vim", "-R", "-"]; fn main() { let matches = App::new("igrepper") .version("1.3.1") .about("The interactive grepper") .arg( Arg::with_name("regex") .short("e") .long("regex") .value_name("REGEX") .help("Regular expression to preload") .takes_value(true), ) .arg( Arg::with_name("context") .short("c") .long("context") .value_name("CONTEXT") .help("Print CONTEXT num of output context") .takes_value(true), ) .arg( Arg::with_name("file") .help("Sets the input file to use. If not set, reads from stdin.") .index(1), ) .arg( Arg::with_name("word") .short("w") .long("word") .conflicts_with("regex") .help("Preload the regular expression '\\S+'"), ) .arg( Arg::with_name("follow") .short("f") .long("follow") .requires("file") .help("Reload the file as it changes. Requires [file] to be set."), ) .get_matches(); let file_option = matches.value_of("file"); let is_tty = unsafe { libc::isatty(libc::STDIN_FILENO as i32) } != 0; let mut file_path: Option<&str> = None; let source_producer: SourceProducer = if is_tty { let path = file_option.unwrap_or_else(|| { eprintln!("{}", PARAMETER_ERROR); std::process::exit(1); }); file_path = Some(path); SourceProducer { input: SourceInput::FilePath(path.to_string()), } } else { if file_option != None { eprintln!("{}", PARAMETER_ERROR); std::process::exit(1); } let source = file_reading::read_source_from_stdin(); reopen_stdin(); SourceProducer { input: SourceInput::FullInput(source), } }; let context: u32 = match matches.value_of("context") { None => 0, Some(context_string) => context_string.parse::<u32>().unwrap(), }; let initial_regex = if matches.is_present("word") { Some("\\S+") } else { matches.value_of("regex") }; let inotify = if matches.is_present("follow") { let mut inotify = Inotify::init() .expect("Failed to monitor file changes, error while initializing inotify instance"); inotify .add_watch( file_path.unwrap(), WatchMask::MODIFY | WatchMask::CLOSE_WRITE, ) .expect("Failed to add file watch"); Some(inotify) } else { None }; let external_editor: Vec<String> = get_external_editor(); igrepper( source_producer, context, initial_regex, inotify, external_editor, ); } fn get_external_editor() -> Vec<String> { if let Ok(a) = env::var("IGREPPER_EDITOR") { let editor_command: Vec<String> = a.split_ascii_whitespace().map(|s| s.to_string()).collect(); if editor_command.len() > 0 { return editor_command; } } DEFAULT_EDITOR_COMMAND .iter() .map(|s| s.to_string()) .collect() } fn reopen_stdin() { unsafe { let close_returncode = close(0); assert_eq!(close_returncode, 0, "Failed to close stdin"); let ptr = "/dev/tty\0".as_ptr() as *const i8; let open_returncode = open(ptr, 0); assert_eq!(open_returncode, 0, "Failed to open /dev/tty"); } }
extern crate clap; extern crate libc; use clap::{App, Arg}; use inotify::{Inotify, WatchMask}; use libc::close; use libc::open; use std::env; use crate::igrepper::igrepper; use file_reading::{SourceInput, SourceProducer}; mod file_reading; mod igrepper; const PARAMETER_ERROR: &str = "Data can only be passed by STDIN if no file parameter is specified"; const DEFAULT_EDITOR_COMMAND: [&str; 3] = ["vim", "-R", "-"]
.requires("file") .help("Reload the file as it changes. Requires [file] to be set."), ) .get_matches(); let file_option = matches.value_of("file"); let is_tty = unsafe { libc::isatty(libc::STDIN_FILENO as i32) } != 0; let mut file_path: Option<&str> = None; let source_producer: SourceProducer = if is_tty { let path = file_option.unwrap_or_else(|| { eprintln!("{}", PARAMETER_ERROR); std::process::exit(1); }); file_path = Some(path); SourceProducer { input: SourceInput::FilePath(path.to_string()), } } else { if file_option != None { eprintln!("{}", PARAMETER_ERROR); std::process::exit(1); } let source = file_reading::read_source_from_stdin(); reopen_stdin(); SourceProducer { input: SourceInput::FullInput(source), } }; let context: u32 = match matches.value_of("context") { None => 0, Some(context_string) => context_string.parse::<u32>().unwrap(), }; let initial_regex = if matches.is_present("word") { Some("\\S+") } else { matches.value_of("regex") }; let inotify = if matches.is_present("follow") { let mut inotify = Inotify::init() .expect("Failed to monitor file changes, error while initializing inotify instance"); inotify .add_watch( file_path.unwrap(), WatchMask::MODIFY | WatchMask::CLOSE_WRITE, ) .expect("Failed to add file watch"); Some(inotify) } else { None }; let external_editor: Vec<String> = get_external_editor(); igrepper( source_producer, context, initial_regex, inotify, external_editor, ); } fn get_external_editor() -> Vec<String> { if let Ok(a) = env::var("IGREPPER_EDITOR") { let editor_command: Vec<String> = a.split_ascii_whitespace().map(|s| s.to_string()).collect(); if editor_command.len() > 0 { return editor_command; } } DEFAULT_EDITOR_COMMAND .iter() .map(|s| s.to_string()) .collect() } fn reopen_stdin() { unsafe { let close_returncode = close(0); assert_eq!(close_returncode, 0, "Failed to close stdin"); let ptr = "/dev/tty\0".as_ptr() as *const i8; let open_returncode = open(ptr, 0); assert_eq!(open_returncode, 0, "Failed to open /dev/tty"); } }
; fn main() { let matches = App::new("igrepper") .version("1.3.1") .about("The interactive grepper") .arg( Arg::with_name("regex") .short("e") .long("regex") .value_name("REGEX") .help("Regular expression to preload") .takes_value(true), ) .arg( Arg::with_name("context") .short("c") .long("context") .value_name("CONTEXT") .help("Print CONTEXT num of output context") .takes_value(true), ) .arg( Arg::with_name("file") .help("Sets the input file to use. If not set, reads from stdin.") .index(1), ) .arg( Arg::with_name("word") .short("w") .long("word") .conflicts_with("regex") .help("Preload the regular expression '\\S+'"), ) .arg( Arg::with_name("follow") .short("f") .long("follow")
random
[ { "content": "fn read_source_from_file(file_path: &str) -> io::Result<Vec<String>> {\n\n let file = File::open(file_path)?;\n\n let reader = BufReader::new(file);\n\n let source: Vec<String> = reader.lines().filter_map(|line| line.ok()).collect();\n\n Ok(source)\n\n}\n\n\n", "file_path": "src/fi...
Rust
src/lib.rs
aymgm/Mirach
c10f00ed06de0b5ab925b54318e7b5c2e2f14352
#![allow(unused)] extern crate symbol; extern crate thiserror; use std::collections::HashMap; use symbol::Symbol; use thiserror::Error; mod llvm_wrapper; use llvm_wrapper as llvm; mod scope_stack; use scope_stack::{ScopeStack, ScopedValue}; mod func_stack; use func_stack::{FuncStackElem, FuncStack}; mod loop_stack; use loop_stack::LoopStackElem; #[cfg(test)] mod unit_tests; pub type Meta = (u32, u32, u32); #[derive(Error, Debug)] pub enum MirErr { #[error("Cannot create local variable at global scope")] LocalVarOnGlobal, #[error("`{0}` is not modifiable")] ConstNotModifiable(Symbol), #[error("Symbol `{0}` is not found. ")] SymbolNotFound(Symbol), #[error("Cannot get outer scope than static scope")] LeavingStaticScope, #[error("Must have value")] MustHaveValue, } #[derive(Debug)] pub struct MirTy { ty: Symbol, args: Vec<MirTy> } pub type Mir = Box<MirRaw>; #[derive(Debug)] pub enum MirRaw { Unit(Meta), Bool(bool, Meta), I64(i64, Meta), U64(u64, Meta), F32(f32, Meta), F64(f64, Meta), StrLit(String, Meta), DefConst(Symbol, Mir, Meta), DefVar(Symbol, MirTy, Mir, Meta), StoreVar(Symbol, Mir, Meta), Load(Symbol, Meta), IAdd(Mir, Mir, Meta), ISub(Mir, Mir, Meta), IMul(Mir, Mir, Meta), IDiv(Mir, Mir, bool, Meta), IMod(Mir, Mir, bool, Meta), IEq(Mir, Mir, Meta), INeq(Mir, Mir, Meta), ILt(Mir, Mir, bool, Meta), ILte(Mir, Mir, bool, Meta), IGt(Mir, Mir, bool, Meta), IGte(Mir, Mir,bool, Meta), FAdd(Mir, Mir, Meta), FSub(Mir, Mir, Meta), FMul(Mir, Mir, Meta), FDiv(Mir, Mir, Meta), FMod(Mir, Mir, Meta), LAnd(Mir, Mir, Meta), LOr(Mir, Mir, Meta), LNot(Mir, Meta), If(Mir, Mir, Mir, Meta), IfVoid(Vec<(Mir, Mir)>, Meta), While{label: Option<Symbol>, cond: Mir, body: Mir, meta: Meta}, DoWhile{label: Option<Symbol>, cond: Mir, body: Mir, meta: Meta}, Loop(Option<Symbol>, Mir, Meta), Continue(Option<Symbol>, Meta), Break(Option<Symbol>, Meta), Fun{name: Symbol, ty: MirTy, params: Vec<Symbol>, body: Mir, meta: Meta}, DeclExternFun{name: Symbol, ty: MirTy, meta: Meta}, Call(Mir, Vec<Mir>, Meta), Ret(Mir, Meta), RetUnit(Meta), Seq(Vec<Mir>, Meta), } pub struct Generator { ctx: llvm::Context, m: llvm::Module, b: llvm::Builder, scope_stack: ScopeStack, func_stack: FuncStack, loop_stack: Vec<LoopStackElem>, } impl Generator { fn new(mod_name: String)->Self { use llvm::*; let ctx = Context::new(); let m = Module::new(mod_name, &ctx); let b = Builder::new(&ctx); let scope_stack = ScopeStack::new(); let func_stack = FuncStack::new(); let loop_stack = Vec::new(); Self{ctx, m, b, scope_stack, func_stack, loop_stack} } fn dispose(&mut self) { self.b.dispose(); self.m.dispose(); self.ctx.dispose(); self.scope_stack.clear(); } fn dump_llvm_ir(&mut self) { self.m.dump(); } fn print_llvm_ir_to_file(&mut self, file: String) { self.m.print_to_file(file); } fn verify_module(&self){ self.m.verify(); } fn meta2str(meta: Meta)->String { format!("f{}l{}c{}", meta.0, meta.1, meta.2) } fn gen_ty(&mut self, ty: &MirTy)->llvm::Type { match ty.ty.as_str() { "Unit" => llvm::Type::void(&self.ctx), "Bool" => llvm::Type::int1(&self.ctx), "I8" => llvm::Type::int8(&self.ctx), "I64" => llvm::Type::int64(&self.ctx), "F32" => llvm::Type::float(&self.ctx), "F64" => llvm::Type::double(&self.ctx), "Fun" => { let mut it = ty.args.iter(); let ret_ty = it.next().expect("illegal function parameter"); let param_ty = it.map(|x| self.gen_ty(x)).collect::<Vec<_>>(); llvm::Type::function(self.gen_ty(ret_ty), &param_ty, false) }, "FunVarArgs" => { let mut it = ty.args.iter(); let ret_ty = it.next().expect("illegal function parameter"); let param_ty = it.map(|x| self.gen_ty(x)).collect::<Vec<_>>(); llvm::Type::function(self.gen_ty(ret_ty), &param_ty, true) }, "Ptr" => { let t = if ty.args.is_empty() { llvm::Type::void(&self.ctx) } else { self.gen_ty(&ty.args[0]) }; llvm::Type::ptr(t) }, _ => unimplemented!() } } fn gen(&mut self, mir: Mir)->Result<Option<llvm::Value>, MirErr> { use llvm::*; match *mir { MirRaw::Unit(_) => panic!("Unit can't be compiled"), MirRaw::Bool(b, _) => Ok(Some(Value::int1(&self.ctx, b))), MirRaw::I64(i, _) => Ok(Some(Value::int64(&self.ctx, i))), MirRaw::StrLit(s, _) => Ok(Some(self.b.global_string_ptr(s, "".into()))), MirRaw::DefConst(n, v, _) => { let v = self.gen(v)?.ok_or(MirErr::MustHaveValue)?; self.scope_stack.insert(n, ScopedValue::Const(v)); Ok(Some(v)) }, MirRaw::DefVar(n, t, v, _) => { let v = self.gen(v)?.ok_or(MirErr::MustHaveValue)?; let t = self.gen_ty(&t); let cbb = self.b.get_current_basic_block(); let m = self.func_stack.insert_alloca(&mut self.b, &cbb, &t).unwrap(); self.scope_stack.insert(n, ScopedValue::Var(t, m)); let r = self.scope_stack.set_value(&mut self.b, n, &v)?; Ok(Some(r)) }, MirRaw::StoreVar(n, v, _) => { let v = self.gen(v)?.ok_or(MirErr::MustHaveValue)?; let r = self.scope_stack.set_value(&mut self.b, n, &v)?; Ok(Some(r)) }, MirRaw::Load(n, _) => Ok(Some(self.scope_stack.get_value(&mut self.b, n).expect("variable not found"))), MirRaw::IAdd(l, r, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_iadd(&l, &r, ""))) }, MirRaw::ISub(l, r, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_isub(&l, &r, ""))) }, MirRaw::IMul(l, r, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_imul(&l, &r, ""))) }, MirRaw::IDiv(l, r, u, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_idiv(&l, &r, u,""))) }, MirRaw::IEq(l, r, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_ieq(&l, &r, ""))) }, MirRaw::INeq(l, r, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_ineq(&l, &r, ""))) }, MirRaw::IGt(l, r, u, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_igt(&l, &r, u,""))) }, MirRaw::IGte(l, r, u, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_igte(&l, &r, u,""))) }, MirRaw::ILt(l, r, u, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_ilt(&l, &r, u,""))) }, MirRaw::ILte(l, r, u, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_ilte(&l, &r, u,""))) }, MirRaw::LAnd(l, r, m) => { let f = self.func_stack.get_current().expect("LAnd instruction must be in a function").func; let bb0 = self.b.get_current_basic_block(); let bb1 = self.ctx.append_basic_block_after(&f, &bb0, format!("and_{}_rhs", Self::meta2str(m))); let bb2 = self.ctx.append_basic_block_after(&f, &bb1, format!("and_{}_end", Self::meta2str(m))); self.b.set_position_at_end_of(&bb0); let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; self.b.cond_br(&l, &bb1, &bb2); self.b.set_position_at_end_of(&bb1); let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; self.b.br(&bb2); self.b.set_position_at_end_of(&bb2); let mut phi = self.b.phi(&Type::int1(&self.ctx), ""); phi.add_incomings(&vec![bb0, bb1], &vec![l, r]); Ok(Some(phi.get_value())) }, MirRaw::LOr(l, r, m) => { let f = self.func_stack.get_current().expect("LOr instruction must be in a function").func; let bb0 = self.b.get_current_basic_block(); let bb1 = self.ctx.append_basic_block_after(&f, &bb0, format!("or_{}_rhs", Self::meta2str(m))); let bb2 = self.ctx.append_basic_block_after(&f, &bb1, format!("or_{}_end", Self::meta2str(m))); self.b.set_position_at_end_of(&bb0); let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; self.b.cond_br(&l, &bb2, &bb1); self.b.set_position_at_end_of(&bb1); let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; self.b.br(&bb2); self.b.set_position_at_end_of(&bb2); let mut phi = self.b.phi(&Type::int1(&self.ctx), ""); phi.add_incomings(&vec![bb0, bb1], &vec![l, r]); Ok(Some(phi.get_value())) }, MirRaw::LNot(x, m) => { let x = self.gen(x)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_lnot(&x, ""))) }, MirRaw::If(cond, tbody, fbody, m) => { let f = self.func_stack.get_current().expect("If instruction must be in a function").func; let bb0 = self.b.get_current_basic_block(); let bb1 = self.ctx.append_basic_block_after(&f, &bb0, format!("if_{}_true", Self::meta2str(m))); let bb2 = self.ctx.append_basic_block_after(&f, &bb1, format!("if_{}_false", Self::meta2str(m))); let bb3 = self.ctx.append_basic_block_after(&f, &bb2, format!("if_{}_end", Self::meta2str(m))); self.b.set_position_at_end_of(&bb0); let cond = self.gen(cond)?.expect("condition expression can't be unit"); self.b.cond_br(&cond, &bb1, &bb2); self.b.set_position_at_end_of(&bb1); let tbody = self.gen(tbody)?.expect("true branch of if can't be unit"); self.b.br(&bb3); self.b.set_position_at_end_of(&bb2); let fbody = self.gen(fbody)?.expect("false branch of if can't be unit"); self.b.br(&bb3); self.b.set_position_at_end_of(&bb3); let mut phi = self.b.phi(&tbody.get_type(), ""); phi.add_incomings(&vec![bb1, bb2], &vec![tbody, fbody]); Ok(Some(phi.get_value())) }, MirRaw::IfVoid(bs, m) => { let len = bs.len(); let f = &self.func_stack.get_current().expect("IfVoid insruction must be in a function").func.clone(); let mut bbs = Vec::with_capacity(len); let bb_begin = self.b.get_current_basic_block(); let bb_end = self.ctx.append_basic_block(&f, format!("if_{}_end", Self::meta2str(m))); for i in 0..len { let bb0 = self.ctx.insert_basic_block_before(&bb_end, format!("if_{}_block{}_begin", Self::meta2str(m), i)); let bb1 = if i != len - 1 { self.ctx.insert_basic_block_before(&bb_end, format!("if_{}_block{}_end", Self::meta2str(m), i)) } else { bb_end.clone() }; bbs.push((bb0, bb1)); } self.b.set_position_at_end_of(&bb_begin); for x in bs.into_iter().enumerate() { let (i, (b0, b1)) = x; let (bb0, bb1) = &bbs[i]; let cond = self.gen(b0)?.ok_or(MirErr::MustHaveValue)?; self.b.cond_br(&cond, &bb0, &bb1); self.b.set_position_at_end_of(&bb0); self.gen(b1)?; self.b.br(&bb_end); self.b.set_position_at_end_of(&bb1); } Ok(None) }, MirRaw::Loop(l, b, m) => { let f = self.func_stack.get_current().expect("Loop instruction must be in a function").func; let bb_current = self.b.get_current_basic_block(); let bb_begin = self.ctx.append_basic_block_after(&f, &bb_current, format!("loop_{}_begin", Self::meta2str(m))); let bb_end = self.ctx.append_basic_block_after(&f, &bb_begin, format!("loop_{}_end", Self::meta2str(m))); self.b.set_position_at_end_of(&bb_begin); self.loop_stack.push(LoopStackElem {name: l, begin_bb: bb_begin.clone(), end_bb: bb_end.clone()}); self.scope_stack.enter_scope(); self.gen(b)?; if self.loop_stack.is_empty() || self.loop_stack.last().unwrap().name != l { panic!("loop stack is in unexpected state") } self.scope_stack.leave_scope()?; self.loop_stack.pop(); self.b.br(&bb_begin); self.b.set_position_at_end_of(&bb_end); Ok(None) }, MirRaw::Break(l, m) => { if self.loop_stack.is_empty() { panic!("break is not in a loop") } if let Some(n) = l { let mut iter = self.loop_stack.iter().rev(); while let Some(LoopStackElem{name: loop_label, begin_bb: _, end_bb: e}) = iter.next() { if let Some(n2) = loop_label { if &n == n2 { self.b.br(&e); return Ok(None); } } } panic!(format!("loop labeled {} is not found", n)) } else { let e = self.loop_stack.last().unwrap(); self.b.br(&e.end_bb); return Ok(None); } }, MirRaw::Fun{name, ty, params, body, meta} => { let ty = self.gen_ty(&ty); let f = self.m.add_function(name.as_str(), ty); self.scope_stack.insert(name, ScopedValue::Const(f.clone())); self.scope_stack.enter_scope(); let alloc = self.ctx.append_basic_block(&f, "alloc"); let entry = self.ctx.append_basic_block(&f, "entry"); self.b.set_position_at_end_of(&alloc); self.b.set_position_at_end_of(&entry); self.func_stack.push(FuncStackElem{func: f.clone(), alloca_bb: alloc.clone()}); let mut i: u32 = 0; for p in params { let v = f.get_param(i); self.scope_stack.insert(p, ScopedValue::Const(v)); i += 1; } self.gen(body)?; let current_bb = self.b.get_current_basic_block(); self.b.set_position_at_end_of(&alloc); self.b.br(&entry); self.b.set_position_at_end_of(&current_bb); self.func_stack.pop(); self.scope_stack.leave_scope()?; Ok(Some(f)) }, MirRaw::DeclExternFun{name, ty, meta} => { let ty = self.gen_ty(&ty); let f = self.m.add_function(name.as_str(), ty); self.scope_stack.insert(name, ScopedValue::Const(f.clone())); Ok(Some(f)) }, MirRaw::Ret(val, meta) => { let v = self.gen(val)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.ret(&v))) }, MirRaw::RetUnit(meta) => { Ok(Some(self.b.ret_void())) }, MirRaw::Call(fun, args, meta) => { let mut a = vec!(); for x in args.into_iter() { a.push(self.gen(x)?.ok_or(MirErr::MustHaveValue)?) } let f = self.gen(fun)?.ok_or(MirErr::MustHaveValue)?; let name = ""; Ok(Some(self.b.call(&f, &a, name))) }, MirRaw::Seq(es, meta) => { if es.is_empty() {panic!("Seq never empty"); } let mut r = None; for e in es { r = self.gen(e)?; } Ok(r) }, _ => unimplemented!() } } } #[macro_export] macro_rules! ast { ( $id:ident : $($arg:expr),* ) => ( Mir::new(MirRaw::$id($($arg),*, (0,line!(),column!()))) ); ( $id:ident # $($name:ident : $arg:expr),* ) => { Mir::new(MirRaw::$id{$($name: $arg),*, meta: (0,line!(),column!())}) }; ( $($arg:expr);* ) => { Mir::new(MirRaw::Seq(vec![$($arg),*], (0,line!(),column!()))) }; } #[macro_export] macro_rules! ty { ([ $id:ident ]) => { MirTy{ty: stringify!($id).into(), args: vec![]}; }; ([$id:ident : $($t:tt),* ]) => { MirTy{ty: stringify!($id).into(), args: vec![$(ty!($t)),*]}; }; }
#![allow(unused)] extern crate symbol; extern crate thiserror; use std::collections::HashMap; use symbol::Symbol; use thiserror::Error; mod llvm_wrapper; use llvm_wrapper as llvm; mod scope_stack; use scope_stack::{ScopeStack, ScopedValue}; mod func_stack; use func_stack::{FuncStackElem, FuncStack}; mod loop_stack; use loop_stack::LoopStackElem; #[cfg(test)] mod unit_tests; pub type Meta = (u32, u32, u32); #[derive(Error, Debug)] pub enum MirErr { #[error("Cannot create local variable at global scope")] LocalVarOnGlobal, #[error("`{0}` is not modifiable")] ConstNotModifiable(Symbol), #[error("Symbol `{0}` is not found. ")] SymbolNotFound(Symbol), #[error("Cannot get outer scope than static scope")] LeavingStaticScope, #[error("Must have value")] MustHaveValue, } #[derive(Debug)] pub struct MirTy { ty: Symbol, args: Vec<MirTy> } pub type Mir = Box<MirRaw>; #[derive(Debug)] pub enum MirRaw { Unit(Meta), Bool(bool, Meta), I64(i64, Meta), U64(u64, Meta), F32(f32, Meta), F64(f64, Meta), StrLit(String, Meta), DefConst(Symbol, Mir, Meta), DefVar(Symbol, MirTy, Mir, Meta), StoreVar(Symbol, Mir, Meta), Load(Symbol, Meta), IAdd(Mir, Mir, Meta), ISub(Mir, Mir, Meta), IMul(Mir, Mir, Meta), IDiv(Mir, Mir, bool, Meta), IMod(Mir, Mir, bool, Meta), IEq(Mir, Mir, Meta), INeq(Mir, Mir, Meta), ILt(Mir, Mir, bool, Meta), ILte(Mir, Mir, bool, Meta), IGt(Mir, Mir, bool, Meta), IGte(Mir, Mir,bool, Meta), FAdd(Mir, Mir, Meta), FSub(Mir, Mir, Meta), FMul(Mir, Mir, Meta), FDiv(Mir, Mir, Meta), FMod(Mir, Mir, Meta), LAnd(Mir, Mir, Meta), LOr(Mir, Mir, Meta), LNot(Mir, Meta), If(Mir, Mir, Mir, Meta), IfVoid(Vec<(Mir, Mir)>, Meta), While{label: Option<Symbol>, cond: Mir, body: Mir, meta: Meta}, DoWhile{label: Option<Symbol>, cond: Mir, body: Mir, meta: Meta}, Loop(Option<Symbol>, Mir, Meta), Continue(Option<Symbol>, Meta), Break(Option<Symbol>, Meta), Fun{name: Symbol, ty: MirTy, params: Vec<Symbol>, body: Mir, meta: Meta}, DeclExternFun{name: Symbol, ty: MirTy, meta: Meta}, Call(Mir, Vec<Mir>, Meta), Ret(Mir, Meta), RetUnit(Meta), Seq(Vec<Mir>, Meta), } pub struct Generator { ctx: llvm::Context, m: llvm::Module, b: llvm::Builder, scope_stack: ScopeStack, func_stack: FuncStack, loop_stack: Vec<LoopStackElem>, } impl Generator { fn new(mod_name: String)->Self { use llvm::*; let ctx = Context::new(); let m = Module::new(mod_name, &ctx); let b = Builder::new(&ctx); let scope_stack = ScopeStack::new(); let func_stack = FuncStack::new(); let loop_stack = Vec::new(); Self{ctx, m, b, scope_stack, func_stack, loop_stack} } fn dispose(&mut self) { self.b.dispose(); self.m.dispose(); self.ctx.dispose(); self.scope_stack.clear(); } fn dump_llvm_ir(&mut self) { self.m.dump(); } fn print_llvm_ir_to_file(&mut self, file: String) { self.m.print_to_file(file); } fn verify_module(&self){ self.m.verify(); } fn meta2str(meta: Meta)->String { format!("f{}l{}c{}", meta.0, meta.1, meta.2) } fn gen_ty(&mut self, ty: &MirTy)->llvm::Type { match ty.ty.as_str() { "Unit" => llvm::Type::void(&self.ctx), "Bool" => llvm::Type::int1(&self.ctx), "I8" => llvm::Type::int8(&self.ctx), "I64" => llvm::Type::int64(&self.ctx), "F32" => llvm::Type::float(&self.ctx), "F64" => llvm::Type::double(&self.ctx), "Fun" => { let mut it = ty.args.iter(); let ret_ty = it.next().expect("illegal function parameter"); let param_ty = it.map(|x| self.gen_ty(x)).collect::<Vec<_>>(); llvm::Type::function(self.gen_ty(ret_ty), &param_ty, false) }, "FunVarArgs" => { let mut it = ty.args.iter(); let ret_ty = it.next().expect("illegal function parameter"); let param_ty = it.map(|x| self.gen_ty(x)).collect::<Vec<_>>(); llvm::Type::function(self.gen_ty(ret_ty), &param_ty, true) }, "Ptr" => { let t =
; llvm::Type::ptr(t) }, _ => unimplemented!() } } fn gen(&mut self, mir: Mir)->Result<Option<llvm::Value>, MirErr> { use llvm::*; match *mir { MirRaw::Unit(_) => panic!("Unit can't be compiled"), MirRaw::Bool(b, _) => Ok(Some(Value::int1(&self.ctx, b))), MirRaw::I64(i, _) => Ok(Some(Value::int64(&self.ctx, i))), MirRaw::StrLit(s, _) => Ok(Some(self.b.global_string_ptr(s, "".into()))), MirRaw::DefConst(n, v, _) => { let v = self.gen(v)?.ok_or(MirErr::MustHaveValue)?; self.scope_stack.insert(n, ScopedValue::Const(v)); Ok(Some(v)) }, MirRaw::DefVar(n, t, v, _) => { let v = self.gen(v)?.ok_or(MirErr::MustHaveValue)?; let t = self.gen_ty(&t); let cbb = self.b.get_current_basic_block(); let m = self.func_stack.insert_alloca(&mut self.b, &cbb, &t).unwrap(); self.scope_stack.insert(n, ScopedValue::Var(t, m)); let r = self.scope_stack.set_value(&mut self.b, n, &v)?; Ok(Some(r)) }, MirRaw::StoreVar(n, v, _) => { let v = self.gen(v)?.ok_or(MirErr::MustHaveValue)?; let r = self.scope_stack.set_value(&mut self.b, n, &v)?; Ok(Some(r)) }, MirRaw::Load(n, _) => Ok(Some(self.scope_stack.get_value(&mut self.b, n).expect("variable not found"))), MirRaw::IAdd(l, r, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_iadd(&l, &r, ""))) }, MirRaw::ISub(l, r, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_isub(&l, &r, ""))) }, MirRaw::IMul(l, r, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_imul(&l, &r, ""))) }, MirRaw::IDiv(l, r, u, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_idiv(&l, &r, u,""))) }, MirRaw::IEq(l, r, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_ieq(&l, &r, ""))) }, MirRaw::INeq(l, r, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_ineq(&l, &r, ""))) }, MirRaw::IGt(l, r, u, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_igt(&l, &r, u,""))) }, MirRaw::IGte(l, r, u, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_igte(&l, &r, u,""))) }, MirRaw::ILt(l, r, u, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_ilt(&l, &r, u,""))) }, MirRaw::ILte(l, r, u, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_ilte(&l, &r, u,""))) }, MirRaw::LAnd(l, r, m) => { let f = self.func_stack.get_current().expect("LAnd instruction must be in a function").func; let bb0 = self.b.get_current_basic_block(); let bb1 = self.ctx.append_basic_block_after(&f, &bb0, format!("and_{}_rhs", Self::meta2str(m))); let bb2 = self.ctx.append_basic_block_after(&f, &bb1, format!("and_{}_end", Self::meta2str(m))); self.b.set_position_at_end_of(&bb0); let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; self.b.cond_br(&l, &bb1, &bb2); self.b.set_position_at_end_of(&bb1); let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; self.b.br(&bb2); self.b.set_position_at_end_of(&bb2); let mut phi = self.b.phi(&Type::int1(&self.ctx), ""); phi.add_incomings(&vec![bb0, bb1], &vec![l, r]); Ok(Some(phi.get_value())) }, MirRaw::LOr(l, r, m) => { let f = self.func_stack.get_current().expect("LOr instruction must be in a function").func; let bb0 = self.b.get_current_basic_block(); let bb1 = self.ctx.append_basic_block_after(&f, &bb0, format!("or_{}_rhs", Self::meta2str(m))); let bb2 = self.ctx.append_basic_block_after(&f, &bb1, format!("or_{}_end", Self::meta2str(m))); self.b.set_position_at_end_of(&bb0); let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; self.b.cond_br(&l, &bb2, &bb1); self.b.set_position_at_end_of(&bb1); let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; self.b.br(&bb2); self.b.set_position_at_end_of(&bb2); let mut phi = self.b.phi(&Type::int1(&self.ctx), ""); phi.add_incomings(&vec![bb0, bb1], &vec![l, r]); Ok(Some(phi.get_value())) }, MirRaw::LNot(x, m) => { let x = self.gen(x)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_lnot(&x, ""))) }, MirRaw::If(cond, tbody, fbody, m) => { let f = self.func_stack.get_current().expect("If instruction must be in a function").func; let bb0 = self.b.get_current_basic_block(); let bb1 = self.ctx.append_basic_block_after(&f, &bb0, format!("if_{}_true", Self::meta2str(m))); let bb2 = self.ctx.append_basic_block_after(&f, &bb1, format!("if_{}_false", Self::meta2str(m))); let bb3 = self.ctx.append_basic_block_after(&f, &bb2, format!("if_{}_end", Self::meta2str(m))); self.b.set_position_at_end_of(&bb0); let cond = self.gen(cond)?.expect("condition expression can't be unit"); self.b.cond_br(&cond, &bb1, &bb2); self.b.set_position_at_end_of(&bb1); let tbody = self.gen(tbody)?.expect("true branch of if can't be unit"); self.b.br(&bb3); self.b.set_position_at_end_of(&bb2); let fbody = self.gen(fbody)?.expect("false branch of if can't be unit"); self.b.br(&bb3); self.b.set_position_at_end_of(&bb3); let mut phi = self.b.phi(&tbody.get_type(), ""); phi.add_incomings(&vec![bb1, bb2], &vec![tbody, fbody]); Ok(Some(phi.get_value())) }, MirRaw::IfVoid(bs, m) => { let len = bs.len(); let f = &self.func_stack.get_current().expect("IfVoid insruction must be in a function").func.clone(); let mut bbs = Vec::with_capacity(len); let bb_begin = self.b.get_current_basic_block(); let bb_end = self.ctx.append_basic_block(&f, format!("if_{}_end", Self::meta2str(m))); for i in 0..len { let bb0 = self.ctx.insert_basic_block_before(&bb_end, format!("if_{}_block{}_begin", Self::meta2str(m), i)); let bb1 = if i != len - 1 { self.ctx.insert_basic_block_before(&bb_end, format!("if_{}_block{}_end", Self::meta2str(m), i)) } else { bb_end.clone() }; bbs.push((bb0, bb1)); } self.b.set_position_at_end_of(&bb_begin); for x in bs.into_iter().enumerate() { let (i, (b0, b1)) = x; let (bb0, bb1) = &bbs[i]; let cond = self.gen(b0)?.ok_or(MirErr::MustHaveValue)?; self.b.cond_br(&cond, &bb0, &bb1); self.b.set_position_at_end_of(&bb0); self.gen(b1)?; self.b.br(&bb_end); self.b.set_position_at_end_of(&bb1); } Ok(None) }, MirRaw::Loop(l, b, m) => { let f = self.func_stack.get_current().expect("Loop instruction must be in a function").func; let bb_current = self.b.get_current_basic_block(); let bb_begin = self.ctx.append_basic_block_after(&f, &bb_current, format!("loop_{}_begin", Self::meta2str(m))); let bb_end = self.ctx.append_basic_block_after(&f, &bb_begin, format!("loop_{}_end", Self::meta2str(m))); self.b.set_position_at_end_of(&bb_begin); self.loop_stack.push(LoopStackElem {name: l, begin_bb: bb_begin.clone(), end_bb: bb_end.clone()}); self.scope_stack.enter_scope(); self.gen(b)?; if self.loop_stack.is_empty() || self.loop_stack.last().unwrap().name != l { panic!("loop stack is in unexpected state") } self.scope_stack.leave_scope()?; self.loop_stack.pop(); self.b.br(&bb_begin); self.b.set_position_at_end_of(&bb_end); Ok(None) }, MirRaw::Break(l, m) => { if self.loop_stack.is_empty() { panic!("break is not in a loop") } if let Some(n) = l { let mut iter = self.loop_stack.iter().rev(); while let Some(LoopStackElem{name: loop_label, begin_bb: _, end_bb: e}) = iter.next() { if let Some(n2) = loop_label { if &n == n2 { self.b.br(&e); return Ok(None); } } } panic!(format!("loop labeled {} is not found", n)) } else { let e = self.loop_stack.last().unwrap(); self.b.br(&e.end_bb); return Ok(None); } }, MirRaw::Fun{name, ty, params, body, meta} => { let ty = self.gen_ty(&ty); let f = self.m.add_function(name.as_str(), ty); self.scope_stack.insert(name, ScopedValue::Const(f.clone())); self.scope_stack.enter_scope(); let alloc = self.ctx.append_basic_block(&f, "alloc"); let entry = self.ctx.append_basic_block(&f, "entry"); self.b.set_position_at_end_of(&alloc); self.b.set_position_at_end_of(&entry); self.func_stack.push(FuncStackElem{func: f.clone(), alloca_bb: alloc.clone()}); let mut i: u32 = 0; for p in params { let v = f.get_param(i); self.scope_stack.insert(p, ScopedValue::Const(v)); i += 1; } self.gen(body)?; let current_bb = self.b.get_current_basic_block(); self.b.set_position_at_end_of(&alloc); self.b.br(&entry); self.b.set_position_at_end_of(&current_bb); self.func_stack.pop(); self.scope_stack.leave_scope()?; Ok(Some(f)) }, MirRaw::DeclExternFun{name, ty, meta} => { let ty = self.gen_ty(&ty); let f = self.m.add_function(name.as_str(), ty); self.scope_stack.insert(name, ScopedValue::Const(f.clone())); Ok(Some(f)) }, MirRaw::Ret(val, meta) => { let v = self.gen(val)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.ret(&v))) }, MirRaw::RetUnit(meta) => { Ok(Some(self.b.ret_void())) }, MirRaw::Call(fun, args, meta) => { let mut a = vec!(); for x in args.into_iter() { a.push(self.gen(x)?.ok_or(MirErr::MustHaveValue)?) } let f = self.gen(fun)?.ok_or(MirErr::MustHaveValue)?; let name = ""; Ok(Some(self.b.call(&f, &a, name))) }, MirRaw::Seq(es, meta) => { if es.is_empty() {panic!("Seq never empty"); } let mut r = None; for e in es { r = self.gen(e)?; } Ok(r) }, _ => unimplemented!() } } } #[macro_export] macro_rules! ast { ( $id:ident : $($arg:expr),* ) => ( Mir::new(MirRaw::$id($($arg),*, (0,line!(),column!()))) ); ( $id:ident # $($name:ident : $arg:expr),* ) => { Mir::new(MirRaw::$id{$($name: $arg),*, meta: (0,line!(),column!())}) }; ( $($arg:expr);* ) => { Mir::new(MirRaw::Seq(vec![$($arg),*], (0,line!(),column!()))) }; } #[macro_export] macro_rules! ty { ([ $id:ident ]) => { MirTy{ty: stringify!($id).into(), args: vec![]}; }; ([$id:ident : $($t:tt),* ]) => { MirTy{ty: stringify!($id).into(), args: vec![$(ty!($t)),*]}; }; }
if ty.args.is_empty() { llvm::Type::void(&self.ctx) } else { self.gen_ty(&ty.args[0]) }
if_condition
[ { "content": "fn run(name: String, mir: Mir)-> String {\n\n use std::process::*;\n\n use llvm_sys::target_machine::*;\n\n use llvm_wrapper::TargetMachine;\n\n let test_data_dir = \"testdata\";\n\n let prefix = if cfg!(target_os = \"windows\") {format!(\"{}\\\\\", test_data_dir)} else {format!(\"{...
Rust
src/textures/render_texture.rs
e0328eric/dioteko
e1f4e017c449d0904ff722f2e3f58ea3a1489b98
use std::cell::Cell; use std::ptr::NonNull; use crate::ffi; pub(crate) struct RenderTextureRc { strong: Cell<usize>, weak: Cell<usize>, } impl RenderTextureRc { fn new() -> Self { Self { strong: Cell::new(1), weak: Cell::new(1), } } } trait RenderTextureRcControll { fn get_strong(&self) -> &Cell<usize>; fn get_weak(&self) -> &Cell<usize>; #[inline] fn strong(&self) -> usize { self.get_strong().get() } #[inline] fn weak(&self) -> usize { self.get_weak().get() } #[inline] fn inc_strong(&self) { self.get_strong().set(self.strong() + 1); } #[inline] fn dec_strong(&self) { self.get_strong().set(self.strong() - 1); } #[inline] fn inc_weak(&self) { self.get_weak().set(self.weak() + 1); } #[inline] fn dec_weak(&self) { self.get_weak().set(self.weak() - 1); } } pub struct RenderTexture { render_texture: ffi::RenderTexture, rc_count: NonNull<RenderTextureRc>, } pub type RenderTexture2D = RenderTexture; impl RenderTexture { pub fn load(width: i32, height: i32) -> Self { Self { render_texture: unsafe { ffi::LoadRenderTexture(width, height) }, rc_count: Box::leak(Box::new(RenderTextureRc::new())).into(), } } pub fn downgrade(val: &Self) -> WeakRenderTexture { val.inc_weak(); WeakRenderTexture { render_texture: val.render_texture, rc_count: val.rc_count, } } #[allow(dead_code)] #[inline] pub(crate) unsafe fn into_raw(self) -> (ffi::RenderTexture, NonNull<RenderTextureRc>) { (self.render_texture, self.rc_count) } #[allow(dead_code)] #[inline] pub(crate) unsafe fn from_raw( render_texture: ffi::RenderTexture, rc_count: NonNull<RenderTextureRc>, ) -> Self { Self { render_texture, rc_count, } } } impl Drop for RenderTexture { fn drop(&mut self) { self.dec_strong(); if self.strong() == 0 { unsafe { ffi::UnloadRenderTexture(self.render_texture) } self.dec_weak(); if self.weak() == 0 { drop(unsafe { Box::from_raw(self.rc_count.as_ptr()) }) } } } } pub struct WeakRenderTexture { render_texture: ffi::RenderTexture, rc_count: NonNull<RenderTextureRc>, } pub type WeakRenderTexture2D = WeakRenderTexture; impl WeakRenderTexture { pub fn upgrade(&self) -> Option<RenderTexture> { if self.strong() != 0 { Some(RenderTexture { render_texture: self.render_texture, rc_count: self.rc_count, }) } else { None } } #[allow(dead_code)] #[inline] pub(crate) unsafe fn into_raw(self) -> (ffi::RenderTexture, NonNull<RenderTextureRc>) { (self.render_texture, self.rc_count) } #[allow(dead_code)] #[inline] pub(crate) unsafe fn from_raw( render_texture: ffi::RenderTexture, rc_count: NonNull<RenderTextureRc>, ) -> Self { Self { render_texture, rc_count, } } } impl Clone for WeakRenderTexture { fn clone(&self) -> Self { self.inc_weak(); Self { render_texture: self.render_texture, rc_count: self.rc_count, } } } impl Drop for WeakRenderTexture { fn drop(&mut self) { self.dec_weak(); if self.weak() == 0 { drop(unsafe { Box::from_raw(self.rc_count.as_ptr()) }) } } } impl RenderTextureRcControll for RenderTexture { fn get_strong(&self) -> &Cell<usize> { unsafe { &self.rc_count.as_ref().strong } } fn get_weak(&self) -> &Cell<usize> { unsafe { &self.rc_count.as_ref().weak } } } impl RenderTextureRcControll for WeakRenderTexture { fn get_strong(&self) -> &Cell<usize> { unsafe { &self.rc_count.as_ref().strong } } fn get_weak(&self) -> &Cell<usize> { unsafe { &self.rc_count.as_ref().weak } } }
use std::cell::Cell; use std::ptr::NonNull; use crate::ffi; pub(crate) struct RenderTextureRc { strong: Cell<usize>, weak: Cell<usize>, } impl RenderTextureRc { fn new() -> Self { Self { strong: Cell::new(1), weak: Cell::new(1), } } } trait RenderTextureRcControll { fn get_strong(&self) -> &Cell<usize>; fn get_weak(&self) -> &Cell<usize>; #[inline] fn strong(&self) -> usize { self.get_strong().get() } #[inline] fn weak(&self) -> usize { self.get_weak().get() } #[inline] fn inc_strong(&self) { self.get_strong().set(self.strong() + 1); } #[inline] fn dec_strong(&self) { self.get_strong().set(self.strong() - 1); } #[inline] fn inc_weak(&self) { self.get_weak().set(self.weak() + 1); } #[inline] fn dec_weak(&self) { self.get_weak().set(self.weak() - 1); } } pub struct RenderTexture { render_texture: ffi::RenderTexture, rc_count: NonNull<RenderTextureRc>, } pub type RenderTexture2D = RenderTexture; impl RenderTexture { pub fn load(width: i32, height: i32) -> Self { Self { render_texture: unsafe { ffi::LoadRenderTexture(width, height) }, rc_count: Box::leak(Box::new(RenderTextureRc::new())).into(), } } pub fn downgrade(val: &Self) -> WeakRenderTexture { val.inc_weak(); WeakRenderTexture { render_texture: val.render_texture, rc_count: val.rc_count, } } #[allow(dead_code)] #[inline] pub(crate) unsafe fn into_raw(self) -> (ffi::RenderTexture, NonNull<RenderTextureRc>) { (self.render_texture, self.rc_count) } #[allow(dead_code)] #[inline] pub(crate) unsafe fn from_raw( render_texture: ffi::RenderTexture, rc_count: NonNull<RenderTextureRc>, ) -> Self { Self { render_texture, rc_count, } } } impl Drop for RenderTexture { fn drop(&mut self) { self.dec_strong(); if self.strong() == 0 { unsafe { ffi::UnloadRenderTexture(self.render_texture) } self.dec_weak(); if self.weak() == 0 { drop(unsafe { Box::from_raw(self.rc_count.as_ptr()) }) } } } } pub struct WeakRenderTexture { render_texture: ffi::RenderTexture, rc_count: NonNull<RenderTextureRc>, } pub type WeakRenderTexture2D = WeakRenderTexture; impl WeakRenderTexture { pub fn upgrade(&self) -> Option<RenderTexture> { if self.strong() != 0 { Some(RenderTexture { render_texture: self.render_texture, rc_count: self.rc_count, }) } else { None } }
render_texture: self.render_texture, rc_count: self.rc_count, } } } impl Drop for WeakRenderTexture { fn drop(&mut self) { self.dec_weak(); if self.weak() == 0 { drop(unsafe { Box::from_raw(self.rc_count.as_ptr()) }) } } } impl RenderTextureRcControll for RenderTexture { fn get_strong(&self) -> &Cell<usize> { unsafe { &self.rc_count.as_ref().strong } } fn get_weak(&self) -> &Cell<usize> { unsafe { &self.rc_count.as_ref().weak } } } impl RenderTextureRcControll for WeakRenderTexture { fn get_strong(&self) -> &Cell<usize> { unsafe { &self.rc_count.as_ref().strong } } fn get_weak(&self) -> &Cell<usize> { unsafe { &self.rc_count.as_ref().weak } } }
#[allow(dead_code)] #[inline] pub(crate) unsafe fn into_raw(self) -> (ffi::RenderTexture, NonNull<RenderTextureRc>) { (self.render_texture, self.rc_count) } #[allow(dead_code)] #[inline] pub(crate) unsafe fn from_raw( render_texture: ffi::RenderTexture, rc_count: NonNull<RenderTextureRc>, ) -> Self { Self { render_texture, rc_count, } } } impl Clone for WeakRenderTexture { fn clone(&self) -> Self { self.inc_weak(); Self {
random
[ { "content": "pub fn get_pixel_data_size(width: i32, height: i32, format: i32) -> i32 {\n\n // SAFETY: ffi\n\n unsafe { ffi::GetPixelDataSize(width, height, format) }\n\n}\n", "file_path": "src/textures/pixel.rs", "rank": 0, "score": 176877.2228604159 }, { "content": "pub fn draw_text(...
Rust
rosetta-i18n/src/serde_helpers.rs
baptiste0928/rosetta
039a69493dc5517d7778b9fb4ed0fa57375cc44e
use std::borrow::Cow; use serde::{de, ser}; use crate::LanguageId; impl ser::Serialize for LanguageId<'_> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer, { serializer.serialize_str(&self.0) } } impl<'de> de::Deserialize<'de> for LanguageId<'de> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: de::Deserializer<'de>, { let value = Cow::deserialize(deserializer)?; match Self::validate(&value) { Some(language_id) => Ok(language_id), None => Err(de::Error::custom(format!( "`{}` is not a valid ISO 693-1 language id", value ))), } } } pub mod as_language { use serde::{de, ser, Deserialize, Serialize}; use crate::{Language, LanguageId}; pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error> where D: de::Deserializer<'de>, T: Language, { let language_id = LanguageId::deserialize(deserializer)?; match T::from_language_id(&language_id) { Some(value) => Ok(value), None => Err(de::Error::custom("language `{}` is not supported")), } } pub fn serialize<S, T>(val: &T, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer, T: Language, { val.language_id().serialize(serializer) } } pub mod as_language_with_fallback { use serde::{de, ser, Deserialize, Serialize}; use crate::{Language, LanguageId}; pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error> where D: de::Deserializer<'de>, T: Language, { let language_id = LanguageId::deserialize(deserializer)?; match T::from_language_id(&language_id) { Some(value) => Ok(value), None => Ok(T::fallback()), } } pub fn serialize<S, T>(val: &T, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer, T: Language, { val.language_id().serialize(serializer) } } #[cfg(test)] mod tests { use serde::{Deserialize, Serialize}; use serde_test::{assert_de_tokens, assert_de_tokens_error, assert_tokens, Token}; use crate::Language; use super::{as_language, as_language_with_fallback, LanguageId}; #[test] fn serde_language_id() { let lang_id = LanguageId::new("en"); assert_tokens(&lang_id, &[Token::String("en")]); } #[test] fn serde_invalid_language_id() { assert_de_tokens_error::<LanguageId>( &[Token::String("invalid")], "`invalid` is not a valid ISO 693-1 language id", ) } #[test] fn serde_as_language() { #[derive(Debug, PartialEq, Eq)] struct Lang; impl Language for Lang { fn from_language_id(language_id: &LanguageId) -> Option<Self> { match language_id.value() { "en" => Some(Self), _ => None, } } fn language_id(&self) -> LanguageId { LanguageId::new("en") } fn fallback() -> Self { unimplemented!() } } #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] struct LanguageStruct { #[serde(with = "as_language")] lang: Lang, } let value = LanguageStruct { lang: Lang }; assert_tokens( &value, &[ Token::Struct { name: "LanguageStruct", len: 1, }, Token::Str("lang"), Token::String("en"), Token::StructEnd, ], ); } #[test] fn serde_as_language_fallback() { #[derive(Debug, PartialEq, Eq)] struct Lang; impl Language for Lang { fn from_language_id(language_id: &LanguageId) -> Option<Self> { match language_id.value() { "en" => Some(Self), _ => None, } } fn language_id(&self) -> LanguageId { LanguageId::new("en") } fn fallback() -> Self { Self } } #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] struct LanguageStruct { #[serde(with = "as_language_with_fallback")] lang: Lang, } let value = LanguageStruct { lang: Lang }; assert_de_tokens( &value, &[ Token::Struct { name: "LanguageStruct", len: 1, }, Token::Str("lang"), Token::String("fr"), Token::StructEnd, ], ); } }
use std::borrow::Cow; use serde::{de, ser}; use crate::LanguageId; impl ser::Serialize for LanguageId<'_> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer, { serializer.serialize_str(&self.0) } } impl<'de> de::Deserialize<'de> for LanguageId<'de> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: de::Deserializer<'de>, { let value = Cow::deserialize(deserializer)?; match Self::validate(&value) { Some(language_id) => Ok(language_id), None => Err(de::Error::custom(format!( "`{}` is not a valid ISO 693-1 language id", value ))), } } } pub mod as_language { use serde::{de, ser, Deserialize, Serialize}; use crate::{Language, LanguageId}; pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error> where D: de::Deserializer<'de>, T: Language, { let language_id = LanguageId::deserialize(deserializer)?; match T::from_language_id(&language_id) { Some(value) => Ok(value), None => Err(de::Error::custom("language `{}` is not supported")), } } pub fn serialize<S, T>(val: &T, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer, T: Language, { val.language_id().serialize(serializer) } } pub mod as_language_with_fallback { use serde::{de, ser, Deserialize, Serialize}; use crate::{Language, LanguageId}; pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error> where D: de::Deserializer<'de>, T: Language, { let language_id = LanguageId::deserialize(deserializer)?; match T::from_language_id(&language_id) { Some(value) => Ok(value), None => Ok(T::fallback()), } } pub fn serialize<S, T>(val: &T, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer, T: Language, { val.language_id().serialize(serializer) } } #[cfg(test)] mod tests { use serde::{Deserialize, Serialize}; use serde_test::{assert_de_tokens, assert_de_tokens_error, assert_tokens, Token}; use crate::Language; use super::{as_language, as_language_with_fallback, LanguageId}; #[test] fn serde_language_id() { let lang_id = LanguageId::new("en"); assert_tokens(&lang_id, &[Token::String("en")]); } #[test] fn serde_invalid_language_id() { assert_de_tokens_error::<LanguageId>( &[Token::String("invalid")], "`invalid` is not a valid ISO 693-1 language id", ) } #[test] fn serde_as_language() { #[derive(Debug, PartialEq, Eq)] struct Lang; impl Language for Lang { fn from_language_id(language_id: &LanguageId) -> Option<Self> { match language_id.value() { "en" => Some(Self), _ => None, } } fn language_id(&self) -> LanguageId { LanguageId::new("en") } fn fallback() -> Self { unimplemented!() } } #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] struct LanguageStruct { #[serde(with = "as_language")] lang: Lang, } let value = LanguageStruct { lang: Lang };
; } #[test] fn serde_as_language_fallback() { #[derive(Debug, PartialEq, Eq)] struct Lang; impl Language for Lang { fn from_language_id(language_id: &LanguageId) -> Option<Self> { match language_id.value() { "en" => Some(Self), _ => None, } } fn language_id(&self) -> LanguageId { LanguageId::new("en") } fn fallback() -> Self { Self } } #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] struct LanguageStruct { #[serde(with = "as_language_with_fallback")] lang: Lang, } let value = LanguageStruct { lang: Lang }; assert_de_tokens( &value, &[ Token::Struct { name: "LanguageStruct", len: 1, }, Token::Str("lang"), Token::String("fr"), Token::StructEnd, ], ); } }
assert_tokens( &value, &[ Token::Struct { name: "LanguageStruct", len: 1, }, Token::Str("lang"), Token::String("en"), Token::StructEnd, ], )
call_expression
[ { "content": "/// Helper function that return an default [`RosettaBuilder`].\n\npub fn config() -> RosettaBuilder {\n\n RosettaBuilder::default()\n\n}\n\n\n\n/// Builder used to configure Rosetta code generation.\n\n#[derive(Debug, Clone, PartialEq, Eq, Default)]\n\npub struct RosettaBuilder {\n\n files: ...
Rust
src/store/encoding/raw/primitive_enc.rs
meerkatdb/meerkat
26ecee08251401fcb240fa6b8d382df590762eae
use std::convert::TryInto; use std::mem::size_of; use anyhow::Result; use async_trait::async_trait; use crate::store::encoding::bitmap_rle; use crate::store::encoding::{BlockEncoder, BlockSink}; use crate::store::indexing_buffer::PrimitiveBuffer; use crate::store::segment_metadata::column_layout::EncoderLayout; use crate::store::segment_metadata::NoLayout; use crate::store::encoding::varint::Encoder as _; pub struct Encoder<T> { remaining: PrimitiveBuffer<T>, encoded_data: Vec<u8>, bitmap_encoder: bitmap_rle::Encoder, min_block_size: usize, num_rows: u32, } impl<T: Send + Sync + Clone> Encoder<T> { pub fn new(block_size: usize, nullable: bool) -> Self { Self { remaining: PrimitiveBuffer::new(nullable), encoded_data: Vec::with_capacity(block_size as usize), bitmap_encoder: bitmap_rle::Encoder::new(), min_block_size: block_size, num_rows: 0, } } async fn write_block<S: BlockSink + Send>( &mut self, buf: &PrimitiveBuffer<T>, start: usize, end: usize, bit_pos: usize, sink: &mut S, ) -> Result<EncodeResult> { let result = encode_primitive_buffer( buf, start, end, bit_pos, &mut self.encoded_data, &mut self.bitmap_encoder, ); self.add_rows(result.num_rows); sink.write_block(self.num_rows - 1, &self.encoded_data) .await?; Ok(result) } async fn write_remaining<S: BlockSink + Send>(&mut self, sink: &mut S) -> Result<EncodeResult> { let result = encode_primitive_buffer( &self.remaining, 0, self.remaining.len(), 0, &mut self.encoded_data, &mut self.bitmap_encoder, ); self.add_rows(result.num_rows); sink.write_block(self.num_rows - 1, &self.encoded_data) .await?; Ok(result) } fn add_rows(&mut self, num_rows: usize) { self.num_rows = self .num_rows .checked_add((num_rows).try_into().expect("segment overflow")) .expect("segment overflow"); } } #[async_trait] impl<T: Send + Sync + Clone, S: BlockSink + Send> BlockEncoder<PrimitiveBuffer<T>, S> for Encoder<T> { async fn encode(&mut self, buffer: &PrimitiveBuffer<T>, sink: &mut S) -> Result<()> { let mut buf_pos = 0; let mut validity_pos = 0; if self.remaining.len() > 0 { let remaining_size = self.remaining.len() * std::mem::size_of::<T>(); let chunk_end = chunk(buffer, 0, self.min_block_size - remaining_size); validity_pos = self.remaining.append_from(buffer, 0, chunk_end, 0); buf_pos = chunk_end; if self.remaining.len() < self.min_block_size { return Ok(()); } self.write_remaining(sink).await?; self.remaining.clear(); } while buf_pos < buffer.len() { let chunk_end = chunk(buffer, buf_pos, self.min_block_size); let chunk_len = chunk_end - buf_pos; let chunk_size = chunk_len * size_of::<T>(); if chunk_size < self.min_block_size { self.remaining .append_from(buffer, buf_pos, chunk_end, validity_pos); return Ok(()); } let result = self .write_block(buffer, buf_pos, chunk_end, validity_pos, sink) .await?; buf_pos = chunk_end; validity_pos = result.last_validity_pos; } Ok(()) } async fn flush(&mut self, sink: &mut S) -> Result<EncoderLayout> { if self.remaining.len() > 0 { self.write_remaining(sink).await?; } Ok(EncoderLayout::Plain(NoLayout {})) } } fn encode_primitive_buffer<T: Clone>( buf: &PrimitiveBuffer<T>, start: usize, end: usize, bit_pos: usize, encoded_data: &mut Vec<u8>, bitmap_encoder: &mut bitmap_rle::Encoder, ) -> EncodeResult { encoded_data.clear(); let block_len = end - start; let block_size = size_of::<T>() * block_len; encoded_data.put_varint(block_size as u64); encoded_data.extend_from_slice(to_byte_slice(&buf.values()[start..end])); match buf.validity() { Some(ref mut validity) => { bitmap_encoder.clear(); let last_bit_pos = bitmap_encoder.put_from(validity, bit_pos, block_len); bitmap_encoder.flush(); encoded_data.extend_from_slice(bitmap_encoder.encoded_values()); EncodeResult { num_rows: last_bit_pos, last_validity_pos: last_bit_pos, } } None => EncodeResult { num_rows: block_len, last_validity_pos: 0, }, } } #[derive(Debug)] struct EncodeResult { num_rows: usize, last_validity_pos: usize, } fn chunk<T: Clone>(buffer: &PrimitiveBuffer<T>, start: usize, min_size: usize) -> usize { let chunk_len = min_size / size_of::<T>() + ((min_size % size_of::<T>() != 0) as usize); let end = start + chunk_len; if end > buffer.len() { return buffer.len(); } end } fn to_byte_slice<'a, T>(src: &'a [T]) -> &'a [u8] { unsafe { std::slice::from_raw_parts::<u8>( src.as_ptr() as *const u8, std::mem::size_of::<T>() * src.len(), ) } } #[cfg(test)] mod test { use crate::store::encoding::test::SinkMock; use super::*; #[tokio::test] async fn test_remaining() { let mut buf: PrimitiveBuffer<i32> = PrimitiveBuffer::new(true); buf.append(10); let mut sink_mock = SinkMock::new(); let mut encoder = Encoder::new(1000, true); encoder.encode(&buf, &mut sink_mock).await.unwrap(); assert_eq!(sink_mock.blocks.len(), 0); encoder.flush(&mut sink_mock).await.unwrap(); assert_eq!(sink_mock.blocks.len(), 1); } #[tokio::test] async fn test_encoder() { let mut buf: PrimitiveBuffer<i32> = PrimitiveBuffer::new(true); for i in 0..1005 { buf.append(i); } let mut sink_mock = SinkMock::new(); let mut encoder = Encoder::new(100, true); encoder.encode(&buf, &mut sink_mock).await.unwrap(); assert_eq!(sink_mock.blocks.len(), 40); encoder.flush(&mut sink_mock).await.unwrap(); assert_eq!(sink_mock.blocks.len(), 41); } }
use std::convert::TryInto; use std::mem::size_of; use anyhow::Result; use async_trait::async_trait; use crate::store::encoding::bitmap_rle; use crate::store::encoding::{BlockEncoder, BlockSink}; use crate::store::indexing_buffer::PrimitiveBuffer; use crate::store::segment_metadata::column_layout::EncoderLayout; use crate::store::segment_metadata::NoLayout; use crate::store::encoding::varint::Encoder as _; pub struct Encoder<T> { remaining: PrimitiveBuffer<T>, encoded_data: Vec<u8>, bitmap_encoder: bitmap_rle::Encoder, min_block_size: usize, num_rows: u32, } impl<T: Send + Sync + Clone> Encoder<T> { pub fn new(block_size: usize, nullable: bool) -> Self { Self { remaining: PrimitiveBuffer::new(nullable), encoded_data: Vec::with_capacity(block_size as usize), bitmap_encoder: bitmap_rle::Encoder::new(), min_block_size: block_size, num_rows: 0, } } async fn write_block<S: BlockSink + Send>( &mut self, buf: &PrimitiveBuffer<T>, start: usize, end: usize, bit_pos: usize, sink: &mut S, ) -> Result<EncodeResult> { let result = encode_primitive_buffer( buf, start, end, bit_pos, &mut self.encoded_data, &mut self.bitmap_encoder, ); self.add_rows(result.num_rows); sink.write_block(self.num_rows - 1, &self.encoded_data) .await?; Ok(result) } async fn write_remaining<S: BlockSink + Send>(&mut self, sink: &mut S) -> Result<EncodeResult> { let result =
; self.add_rows(result.num_rows); sink.write_block(self.num_rows - 1, &self.encoded_data) .await?; Ok(result) } fn add_rows(&mut self, num_rows: usize) { self.num_rows = self .num_rows .checked_add((num_rows).try_into().expect("segment overflow")) .expect("segment overflow"); } } #[async_trait] impl<T: Send + Sync + Clone, S: BlockSink + Send> BlockEncoder<PrimitiveBuffer<T>, S> for Encoder<T> { async fn encode(&mut self, buffer: &PrimitiveBuffer<T>, sink: &mut S) -> Result<()> { let mut buf_pos = 0; let mut validity_pos = 0; if self.remaining.len() > 0 { let remaining_size = self.remaining.len() * std::mem::size_of::<T>(); let chunk_end = chunk(buffer, 0, self.min_block_size - remaining_size); validity_pos = self.remaining.append_from(buffer, 0, chunk_end, 0); buf_pos = chunk_end; if self.remaining.len() < self.min_block_size { return Ok(()); } self.write_remaining(sink).await?; self.remaining.clear(); } while buf_pos < buffer.len() { let chunk_end = chunk(buffer, buf_pos, self.min_block_size); let chunk_len = chunk_end - buf_pos; let chunk_size = chunk_len * size_of::<T>(); if chunk_size < self.min_block_size { self.remaining .append_from(buffer, buf_pos, chunk_end, validity_pos); return Ok(()); } let result = self .write_block(buffer, buf_pos, chunk_end, validity_pos, sink) .await?; buf_pos = chunk_end; validity_pos = result.last_validity_pos; } Ok(()) } async fn flush(&mut self, sink: &mut S) -> Result<EncoderLayout> { if self.remaining.len() > 0 { self.write_remaining(sink).await?; } Ok(EncoderLayout::Plain(NoLayout {})) } } fn encode_primitive_buffer<T: Clone>( buf: &PrimitiveBuffer<T>, start: usize, end: usize, bit_pos: usize, encoded_data: &mut Vec<u8>, bitmap_encoder: &mut bitmap_rle::Encoder, ) -> EncodeResult { encoded_data.clear(); let block_len = end - start; let block_size = size_of::<T>() * block_len; encoded_data.put_varint(block_size as u64); encoded_data.extend_from_slice(to_byte_slice(&buf.values()[start..end])); match buf.validity() { Some(ref mut validity) => { bitmap_encoder.clear(); let last_bit_pos = bitmap_encoder.put_from(validity, bit_pos, block_len); bitmap_encoder.flush(); encoded_data.extend_from_slice(bitmap_encoder.encoded_values()); EncodeResult { num_rows: last_bit_pos, last_validity_pos: last_bit_pos, } } None => EncodeResult { num_rows: block_len, last_validity_pos: 0, }, } } #[derive(Debug)] struct EncodeResult { num_rows: usize, last_validity_pos: usize, } fn chunk<T: Clone>(buffer: &PrimitiveBuffer<T>, start: usize, min_size: usize) -> usize { let chunk_len = min_size / size_of::<T>() + ((min_size % size_of::<T>() != 0) as usize); let end = start + chunk_len; if end > buffer.len() { return buffer.len(); } end } fn to_byte_slice<'a, T>(src: &'a [T]) -> &'a [u8] { unsafe { std::slice::from_raw_parts::<u8>( src.as_ptr() as *const u8, std::mem::size_of::<T>() * src.len(), ) } } #[cfg(test)] mod test { use crate::store::encoding::test::SinkMock; use super::*; #[tokio::test] async fn test_remaining() { let mut buf: PrimitiveBuffer<i32> = PrimitiveBuffer::new(true); buf.append(10); let mut sink_mock = SinkMock::new(); let mut encoder = Encoder::new(1000, true); encoder.encode(&buf, &mut sink_mock).await.unwrap(); assert_eq!(sink_mock.blocks.len(), 0); encoder.flush(&mut sink_mock).await.unwrap(); assert_eq!(sink_mock.blocks.len(), 1); } #[tokio::test] async fn test_encoder() { let mut buf: PrimitiveBuffer<i32> = PrimitiveBuffer::new(true); for i in 0..1005 { buf.append(i); } let mut sink_mock = SinkMock::new(); let mut encoder = Encoder::new(100, true); encoder.encode(&buf, &mut sink_mock).await.unwrap(); assert_eq!(sink_mock.blocks.len(), 40); encoder.flush(&mut sink_mock).await.unwrap(); assert_eq!(sink_mock.blocks.len(), 41); } }
encode_primitive_buffer( &self.remaining, 0, self.remaining.len(), 0, &mut self.encoded_data, &mut self.bitmap_encoder, )
call_expression
[ { "content": "#[inline]\n\npub fn encode_varint(mut value: u64, buf: &mut [u8]) -> usize {\n\n let mut i = 0;\n\n while value >= 0x80 {\n\n buf[i] = ((value & 0x7F) | 0x80) as u8;\n\n value >>= 7;\n\n i += 1;\n\n }\n\n buf[i] = value as u8;\n\n i += 1;\n\n i\n\n}\n\n\n\n//...
Rust
src/filters/tests.rs
dsaxton/feroxbuster
45efaa738850f7644683d927cffc5661e97307c4
use super::*; use ::fuzzyhash::FuzzyHash; use ::regex::Regex; #[test] fn wildcard_filter_default() { let wcf = WildcardFilter::default(); assert_eq!(wcf.size, u64::MAX); assert_eq!(wcf.dynamic, u64::MAX); } #[test] fn wildcard_filter_as_any() { let filter = WildcardFilter::default(); let filter2 = WildcardFilter::default(); assert!(filter.box_eq(filter2.as_any())); assert_eq!( *filter.as_any().downcast_ref::<WildcardFilter>().unwrap(), filter ); } #[test] fn lines_filter_as_any() { let filter = LinesFilter { line_count: 1 }; let filter2 = LinesFilter { line_count: 1 }; assert!(filter.box_eq(filter2.as_any())); assert_eq!(filter.line_count, 1); assert_eq!( *filter.as_any().downcast_ref::<LinesFilter>().unwrap(), filter ); } #[test] fn words_filter_as_any() { let filter = WordsFilter { word_count: 1 }; let filter2 = WordsFilter { word_count: 1 }; assert!(filter.box_eq(filter2.as_any())); assert_eq!(filter.word_count, 1); assert_eq!( *filter.as_any().downcast_ref::<WordsFilter>().unwrap(), filter ); } #[test] fn size_filter_as_any() { let filter = SizeFilter { content_length: 1 }; let filter2 = SizeFilter { content_length: 1 }; assert!(filter.box_eq(filter2.as_any())); assert_eq!(filter.content_length, 1); assert_eq!( *filter.as_any().downcast_ref::<SizeFilter>().unwrap(), filter ); } #[test] fn status_code_filter_as_any() { let filter = StatusCodeFilter { filter_code: 200 }; let filter2 = StatusCodeFilter { filter_code: 200 }; assert!(filter.box_eq(filter2.as_any())); assert_eq!(filter.filter_code, 200); assert_eq!( *filter.as_any().downcast_ref::<StatusCodeFilter>().unwrap(), filter ); } #[test] fn regex_filter_as_any() { let raw = r".*\.txt$"; let compiled = Regex::new(raw).unwrap(); let compiled2 = Regex::new(raw).unwrap(); let filter = RegexFilter { compiled, raw_string: raw.to_string(), }; let filter2 = RegexFilter { compiled: compiled2, raw_string: raw.to_string(), }; assert!(filter.box_eq(filter2.as_any())); assert_eq!(filter.raw_string, r".*\.txt$"); assert_eq!( *filter.as_any().downcast_ref::<RegexFilter>().unwrap(), filter ); } #[test] fn wildcard_should_filter_when_static_wildcard_found() { let mut resp = FeroxResponse::default(); resp.set_wildcard(true); resp.set_url("http://localhost"); resp.set_text( "pellentesque diam volutpat commodo sed egestas egestas fringilla phasellus faucibus", ); let filter = WildcardFilter { size: 83, dynamic: 0, dont_filter: false, }; assert!(filter.should_filter_response(&resp)); } #[test] fn wildcard_should_filter_when_static_wildcard_len_is_zero() { let mut resp = FeroxResponse::default(); resp.set_wildcard(true); resp.set_url("http://localhost"); let filter = WildcardFilter::new(false); assert!(filter.should_filter_response(&resp)); } #[test] fn wildcard_should_filter_when_dynamic_wildcard_found() { let mut resp = FeroxResponse::default(); resp.set_wildcard(true); resp.set_url("http://localhost/stuff"); resp.set_text("pellentesque diam volutpat commodo sed egestas egestas fringilla"); let filter = WildcardFilter { size: 0, dynamic: 59, dont_filter: false, }; println!("resp: {:?}: filter: {:?}", resp, filter); assert!(filter.should_filter_response(&resp)); } #[test] fn regexfilter_should_filter_when_regex_matches_on_response_body() { let mut resp = FeroxResponse::default(); resp.set_url("http://localhost/stuff"); resp.set_text("im a body response hurr durr!"); let raw = r"response...rr"; let filter = RegexFilter { raw_string: raw.to_string(), compiled: Regex::new(raw).unwrap(), }; assert!(filter.should_filter_response(&resp)); } #[test] fn similarity_filter_is_accurate() { let mut resp = FeroxResponse::default(); resp.set_url("http://localhost/stuff"); resp.set_text("sitting"); let mut filter = SimilarityFilter { text: FuzzyHash::new("kitten").to_string(), threshold: 95, }; assert!(!filter.should_filter_response(&resp)); resp.set_text(""); filter.text = String::new(); filter.threshold = 100; assert!(!filter.should_filter_response(&resp)); resp.set_text("some data to hash for the purposes of running a test"); filter.text = FuzzyHash::new("some data to hash for the purposes of running a te").to_string(); filter.threshold = 17; assert!(filter.should_filter_response(&resp)); } #[test] fn similarity_filter_as_any() { let filter = SimilarityFilter { text: String::from("stuff"), threshold: 95, }; let filter2 = SimilarityFilter { text: String::from("stuff"), threshold: 95, }; assert!(filter.box_eq(filter2.as_any())); assert_eq!(filter.text, "stuff"); assert_eq!( *filter.as_any().downcast_ref::<SimilarityFilter>().unwrap(), filter ); }
use super::*; use ::fuzzyhash::FuzzyHash; use ::regex::Regex; #[test] fn wildcard_filter_default() { let wcf = WildcardFilter::default(); assert_eq!(wcf.size, u64::MAX); assert_eq!(wcf.dynamic, u64::MAX); } #[test] fn wildcard_filter_as_any() { let filter = WildcardFilter::default(); let filter2 = WildcardFilter::default(); assert!(filter.box_eq(filter2.as_any())); assert_eq!( *filter.as_any().downcast_ref::<WildcardFilter>().unwrap(), filter ); } #[test] fn lines_filter_as_any() { let filter = LinesFilter { line_count: 1 }; let filter2 = LinesFilter { line_count: 1 }; assert!(filter.box_eq(filter2.as_any())); assert_eq!(filter.line_count, 1); assert_eq!( *filter.as_any().downcast_ref::<LinesFilter>().unwrap(), filter ); } #[test] fn words_filter_as_any() { let filter = WordsFilter { word_count: 1 }; let filter2 = WordsFilter { word_count: 1 }; assert!(filter.box_eq(filter2.as_any())); assert_eq!(filter.word_count, 1); assert_eq!( *filter.as_any().downcast_ref::<WordsFilter>().unwrap(), filter ); } #[test] fn size_filter_as_any() { let filter = SizeFilter { content_length: 1 }; let filter2 = SizeFilter { content_length: 1 }; assert!(filter.box_eq(filter2.as_any())); assert_eq!(filter.content_length, 1); assert_eq!( *filter.as_any().downcast_ref::<SizeFilter>().unwrap(), filter ); } #[test] fn status_code_filter_as_any() { let filter = StatusCodeFilter { filter_code: 200 }; let filter2 = StatusCodeFilter { filter_code: 200 }; assert!(filter.box_eq(filter2.as_any())); assert_eq!(filter.filter_code, 200); assert_eq!( *filter.as_any().downcast_ref::<StatusCodeFilter>().unwrap(), filter ); } #[test] fn regex_filter_as_any() { let raw = r".*\.txt$"; let compiled = Regex::new(raw).unwrap(); let compiled2 = Regex::new(raw).unwrap(); let filter = RegexFilter { compiled, raw_string: raw.to_string(), }; let filter2 = RegexFilter { compiled: compiled2, raw_string: raw.to_string(), }; assert!(filter.box_eq(filter2.as_an
#[test] fn wildcard_should_filter_when_static_wildcard_found() { let mut resp = FeroxResponse::default(); resp.set_wildcard(true); resp.set_url("http://localhost"); resp.set_text( "pellentesque diam volutpat commodo sed egestas egestas fringilla phasellus faucibus", ); let filter = WildcardFilter { size: 83, dynamic: 0, dont_filter: false, }; assert!(filter.should_filter_response(&resp)); } #[test] fn wildcard_should_filter_when_static_wildcard_len_is_zero() { let mut resp = FeroxResponse::default(); resp.set_wildcard(true); resp.set_url("http://localhost"); let filter = WildcardFilter::new(false); assert!(filter.should_filter_response(&resp)); } #[test] fn wildcard_should_filter_when_dynamic_wildcard_found() { let mut resp = FeroxResponse::default(); resp.set_wildcard(true); resp.set_url("http://localhost/stuff"); resp.set_text("pellentesque diam volutpat commodo sed egestas egestas fringilla"); let filter = WildcardFilter { size: 0, dynamic: 59, dont_filter: false, }; println!("resp: {:?}: filter: {:?}", resp, filter); assert!(filter.should_filter_response(&resp)); } #[test] fn regexfilter_should_filter_when_regex_matches_on_response_body() { let mut resp = FeroxResponse::default(); resp.set_url("http://localhost/stuff"); resp.set_text("im a body response hurr durr!"); let raw = r"response...rr"; let filter = RegexFilter { raw_string: raw.to_string(), compiled: Regex::new(raw).unwrap(), }; assert!(filter.should_filter_response(&resp)); } #[test] fn similarity_filter_is_accurate() { let mut resp = FeroxResponse::default(); resp.set_url("http://localhost/stuff"); resp.set_text("sitting"); let mut filter = SimilarityFilter { text: FuzzyHash::new("kitten").to_string(), threshold: 95, }; assert!(!filter.should_filter_response(&resp)); resp.set_text(""); filter.text = String::new(); filter.threshold = 100; assert!(!filter.should_filter_response(&resp)); resp.set_text("some data to hash for the purposes of running a test"); filter.text = FuzzyHash::new("some data to hash for the purposes of running a te").to_string(); filter.threshold = 17; assert!(filter.should_filter_response(&resp)); } #[test] fn similarity_filter_as_any() { let filter = SimilarityFilter { text: String::from("stuff"), threshold: 95, }; let filter2 = SimilarityFilter { text: String::from("stuff"), threshold: 95, }; assert!(filter.box_eq(filter2.as_any())); assert_eq!(filter.text, "stuff"); assert_eq!( *filter.as_any().downcast_ref::<SimilarityFilter>().unwrap(), filter ); }
y())); assert_eq!(filter.raw_string, r".*\.txt$"); assert_eq!( *filter.as_any().downcast_ref::<RegexFilter>().unwrap(), filter ); }
function_block-function_prefixed
[]
Rust
plan_b/src/map.rs
PoHuit/plan-b
12121a5e9c542b2486a2fd33ba06bcebfeba6b65
use std::collections::HashMap; use std::error::Error; use std::fs::File; use std::slice; use libflate::gzip; #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct SystemId(usize); #[derive(Debug)] pub struct SystemInfo { pub system_id: SystemId, pub name: String, pub stargates: Vec<SystemId>, pub system_index: usize, } #[derive(Debug)] pub struct Map { systems: Vec<SystemInfo>, by_system_id: HashMap<SystemId, usize>, by_name: HashMap<String, usize>, } mod json_repr { use std::collections::HashMap; use serde::{de, Deserialize, Deserializer}; use serde_json::{self, Value}; use std::str::FromStr; fn de_from_f64<'de, D>(deserializer: D) -> Result<f64, D::Error> where D: Deserializer<'de>, { let v = Value::deserialize(deserializer)?; let e = "an f64 literal or string"; match v { Value::Number(v) => Ok(v.as_f64().unwrap()), Value::String(s) => f64::from_str(&s).map_err(de::Error::custom), Value::Null => { let ue = de::Unexpected::Other("null"); Err(de::Error::invalid_value(ue, &e)) } Value::Bool(b) => { let ue = de::Unexpected::Bool(b); Err(de::Error::invalid_value(ue, &e)) } Value::Array(_) => { let ue = de::Unexpected::Seq; Err(de::Error::invalid_value(ue, &e)) } Value::Object(_) => { let ue = de::Unexpected::Map; Err(de::Error::invalid_value(ue, &e)) } } } #[derive(Deserialize)] pub struct Destination { pub stargate_id: usize, pub system_id: usize, } #[derive(Deserialize)] pub struct Point { #[serde(deserialize_with = "de_from_f64")] pub x: f64, #[serde(deserialize_with = "de_from_f64")] pub y: f64, #[serde(deserialize_with = "de_from_f64")] pub z: f64, } #[derive(Deserialize)] pub struct Stargate { pub destination: Destination, pub name: String, pub position: Point, pub stargate_id: usize, pub system_id: usize, pub type_id: usize, } #[derive(Deserialize)] pub struct Planet { pub asteroid_belts: Option<Vec<usize>>, pub moons: Option<Vec<usize>>, pub planet_id: usize, } #[derive(Deserialize)] pub struct System { pub constellation_id: usize, pub name: String, pub planets: Option<Vec<Planet>>, pub position: Point, pub security_class: Option<String>, pub security_status: f64, pub star_id: Option<usize>, pub stargates: Option<Vec<usize>>, pub stations: Option<Vec<usize>>, pub system_id: usize, } #[derive(Deserialize)] pub struct Map { pub stargates: HashMap<usize, Stargate>, pub systems: HashMap<usize, System>, } } fn find_map_file() -> Result<File, Box<dyn Error>> { let mut f = None; for fname in [ "./static/eve-map.json.gz", "./eve-map.json.gz", "/usr/local/share/eve-map.json.gz", ] .iter() { f = Some(File::open(fname)); if let Some(Ok(f)) = f { return Ok(f); } } f.unwrap().map_err(|e| Box::new(e) as Box<dyn Error>) } impl Map { pub fn fetch() -> Result<Map, Box<dyn Error>> { let map_file = find_map_file()?; let gunzip = gzip::Decoder::new(map_file)?; let map: json_repr::Map = serde_json::from_reader(gunzip)?; let mut by_system_id = HashMap::new(); let mut by_name = HashMap::new(); let mut systems = Vec::with_capacity(map.systems.len()); let mut system_index = 0; for (system_id, system) in &map.systems { let system_id = SystemId(*system_id); let stargates: Vec<SystemId>; match system.stargates { None => continue, Some(ref stargate_ids) => { stargates = stargate_ids .iter() .map(|s| SystemId(map.stargates[s].destination.system_id)) .collect() } } let system_info = SystemInfo { system_id, name: system.name.clone(), stargates, system_index, }; systems.push(system_info); by_system_id.insert(system_id, system_index); by_name.insert(system.name.clone(), system_index); system_index += 1; } Ok(Map { systems, by_system_id, by_name, }) } pub fn by_name<'a>(&'a self, name: &'a str) -> Option<&'a SystemInfo> { self.by_name.get(name).map(|i| &self.systems[*i]) } pub fn by_system_id(&self, id: SystemId) -> &SystemInfo { let i = self .by_system_id .get(&id) .expect("by_system_id: invalid SystemId"); &self.systems[*i] } pub fn systems(&self) -> slice::Iter<'_, SystemInfo> { self.systems.iter() } pub fn systems_ref(&self) -> &[SystemInfo] { &self.systems } }
use std::collections::HashMap; use std::error::Error; use std::fs::File; use std::slice; use libflate::gzip; #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct SystemId(usize); #[derive(Debug)] pub struct SystemInfo { pub system_id: SystemId, pub name: String, pub stargates: Vec<SystemId>, pub system_index: usize, } #[derive(Debug)] pub struct Map { systems: Vec<SystemInfo>, by_system_id: HashMap<SystemId, usize>, by_name: HashMap<String, usize>, } mod json_repr { use std::collections::HashMap; use serde::{de, Deserialize, Deserializer}; use serde_json::{self, Value}; use std::str::FromStr; fn de_from_f64<'de, D>(deserializer: D) -> Result<f64, D::Error> where D: Deserializer<'de>, { let v = Value::deserialize(deserializer)?; let e = "an f64 literal or string"; match v { Value::Number(v) => Ok(v.as_f64().unwrap()), Value::String(s) => f64::from_str(&s).map_err(de::Error::custom), Value::Null => { let ue = de::Unexpected::Other("null"); Err(de::Error::invalid_value(ue, &e)) } Value::Bool(b) => { let ue = de::Unexpected::Bool(b); Err(de::Error::invalid_value(ue, &e)) }
#[derive(Deserialize)] pub struct Destination { pub stargate_id: usize, pub system_id: usize, } #[derive(Deserialize)] pub struct Point { #[serde(deserialize_with = "de_from_f64")] pub x: f64, #[serde(deserialize_with = "de_from_f64")] pub y: f64, #[serde(deserialize_with = "de_from_f64")] pub z: f64, } #[derive(Deserialize)] pub struct Stargate { pub destination: Destination, pub name: String, pub position: Point, pub stargate_id: usize, pub system_id: usize, pub type_id: usize, } #[derive(Deserialize)] pub struct Planet { pub asteroid_belts: Option<Vec<usize>>, pub moons: Option<Vec<usize>>, pub planet_id: usize, } #[derive(Deserialize)] pub struct System { pub constellation_id: usize, pub name: String, pub planets: Option<Vec<Planet>>, pub position: Point, pub security_class: Option<String>, pub security_status: f64, pub star_id: Option<usize>, pub stargates: Option<Vec<usize>>, pub stations: Option<Vec<usize>>, pub system_id: usize, } #[derive(Deserialize)] pub struct Map { pub stargates: HashMap<usize, Stargate>, pub systems: HashMap<usize, System>, } } fn find_map_file() -> Result<File, Box<dyn Error>> { let mut f = None; for fname in [ "./static/eve-map.json.gz", "./eve-map.json.gz", "/usr/local/share/eve-map.json.gz", ] .iter() { f = Some(File::open(fname)); if let Some(Ok(f)) = f { return Ok(f); } } f.unwrap().map_err(|e| Box::new(e) as Box<dyn Error>) } impl Map { pub fn fetch() -> Result<Map, Box<dyn Error>> { let map_file = find_map_file()?; let gunzip = gzip::Decoder::new(map_file)?; let map: json_repr::Map = serde_json::from_reader(gunzip)?; let mut by_system_id = HashMap::new(); let mut by_name = HashMap::new(); let mut systems = Vec::with_capacity(map.systems.len()); let mut system_index = 0; for (system_id, system) in &map.systems { let system_id = SystemId(*system_id); let stargates: Vec<SystemId>; match system.stargates { None => continue, Some(ref stargate_ids) => { stargates = stargate_ids .iter() .map(|s| SystemId(map.stargates[s].destination.system_id)) .collect() } } let system_info = SystemInfo { system_id, name: system.name.clone(), stargates, system_index, }; systems.push(system_info); by_system_id.insert(system_id, system_index); by_name.insert(system.name.clone(), system_index); system_index += 1; } Ok(Map { systems, by_system_id, by_name, }) } pub fn by_name<'a>(&'a self, name: &'a str) -> Option<&'a SystemInfo> { self.by_name.get(name).map(|i| &self.systems[*i]) } pub fn by_system_id(&self, id: SystemId) -> &SystemInfo { let i = self .by_system_id .get(&id) .expect("by_system_id: invalid SystemId"); &self.systems[*i] } pub fn systems(&self) -> slice::Iter<'_, SystemInfo> { self.systems.iter() } pub fn systems_ref(&self) -> &[SystemInfo] { &self.systems } }
Value::Array(_) => { let ue = de::Unexpected::Seq; Err(de::Error::invalid_value(ue, &e)) } Value::Object(_) => { let ue = de::Unexpected::Map; Err(de::Error::invalid_value(ue, &e)) } } }
function_block-function_prefix_line
[ { "content": "// Look up the given system name in the map, and panic if\n\n// not found. This should be cleaned up.\n\nfn find_system(map: &Map, name: &str) -> SystemId {\n\n map.by_name(name)\n\n .unwrap_or_else(|| panic!(\"could not find {} in map\", name))\n\n .system_id\n\n}\n\n\n", "fi...
Rust
src/keyassignment.rs
bcully/wezterm
ea401e1f58ca5a088ac5d5e1d7963f36269afb76
use crate::config::configuration; use crate::mux::domain::DomainId; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::path::PathBuf; use term::{KeyCode, KeyModifiers}; #[derive(Debug, Clone, Deserialize, Serialize)] pub enum SpawnTabDomain { DefaultDomain, CurrentTabDomain, Domain(DomainId), DomainName(String), } impl Default for SpawnTabDomain { fn default() -> Self { Self::CurrentTabDomain } } #[derive(Default, Debug, Clone, Deserialize, Serialize)] pub struct SpawnCommand { pub label: Option<String>, pub args: Option<Vec<String>>, pub cwd: Option<PathBuf>, #[serde(default)] pub set_environment_variables: HashMap<String, String>, #[serde(default)] pub domain: SpawnTabDomain, } #[derive(Debug, Clone, Deserialize, Serialize)] pub enum KeyAssignment { SpawnTab(SpawnTabDomain), SpawnWindow, ToggleFullScreen, Copy, Paste, ActivateTabRelative(isize), IncreaseFontSize, DecreaseFontSize, ResetFontSize, ActivateTab(usize), SendString(String), Nop, Hide, Show, CloseCurrentTab, ReloadConfiguration, MoveTabRelative(isize), MoveTab(usize), ScrollByPage(isize), ShowTabNavigator, HideApplication, QuitApplication, SpawnCommandInNewTab(SpawnCommand), SpawnCommandInNewWindow(SpawnCommand), ShowLauncher, } pub struct KeyMap(HashMap<(KeyCode, KeyModifiers), KeyAssignment>); impl KeyMap { pub fn new() -> Self { let mut map = configuration() .key_bindings() .expect("keys section of config to be valid"); macro_rules! m { ($([$mod:expr, $code:expr, $action:expr]),* $(,)?) => { $( map.entry(($code, $mod)).or_insert($action); )* }; }; use KeyAssignment::*; let ctrl_shift = KeyModifiers::CTRL | KeyModifiers::SHIFT; m!( [KeyModifiers::SHIFT, KeyCode::Insert, Paste], [KeyModifiers::SUPER, KeyCode::Char('c'), Copy], [KeyModifiers::SUPER, KeyCode::Char('v'), Paste], [ctrl_shift, KeyCode::Char('C'), Copy], [ctrl_shift, KeyCode::Char('V'), Paste], [KeyModifiers::ALT, KeyCode::Char('\n'), ToggleFullScreen], [KeyModifiers::ALT, KeyCode::Char('\r'), ToggleFullScreen], [KeyModifiers::ALT, KeyCode::Enter, ToggleFullScreen], [KeyModifiers::SUPER, KeyCode::Char('m'), Hide], [KeyModifiers::SUPER, KeyCode::Char('n'), SpawnWindow], [ctrl_shift, KeyCode::Char('M'), Hide], [ctrl_shift, KeyCode::Char('N'), SpawnWindow], [KeyModifiers::CTRL, KeyCode::Char('-'), DecreaseFontSize], [KeyModifiers::CTRL, KeyCode::Char('0'), ResetFontSize], [KeyModifiers::CTRL, KeyCode::Char('='), IncreaseFontSize], [KeyModifiers::SUPER, KeyCode::Char('-'), DecreaseFontSize], [KeyModifiers::SUPER, KeyCode::Char('0'), ResetFontSize], [KeyModifiers::SUPER, KeyCode::Char('='), IncreaseFontSize], [ KeyModifiers::SUPER, KeyCode::Char('t'), SpawnTab(SpawnTabDomain::CurrentTabDomain) ], [ ctrl_shift, KeyCode::Char('T'), SpawnTab(SpawnTabDomain::CurrentTabDomain) ], [ KeyModifiers::SUPER | KeyModifiers::SHIFT, KeyCode::Char('T'), SpawnTab(SpawnTabDomain::CurrentTabDomain) ], [KeyModifiers::SUPER, KeyCode::Char('1'), ActivateTab(0)], [KeyModifiers::SUPER, KeyCode::Char('2'), ActivateTab(1)], [KeyModifiers::SUPER, KeyCode::Char('3'), ActivateTab(2)], [KeyModifiers::SUPER, KeyCode::Char('4'), ActivateTab(3)], [KeyModifiers::SUPER, KeyCode::Char('5'), ActivateTab(4)], [KeyModifiers::SUPER, KeyCode::Char('6'), ActivateTab(5)], [KeyModifiers::SUPER, KeyCode::Char('7'), ActivateTab(6)], [KeyModifiers::SUPER, KeyCode::Char('8'), ActivateTab(7)], [KeyModifiers::SUPER, KeyCode::Char('9'), ActivateTab(8)], [KeyModifiers::SUPER, KeyCode::Char('w'), CloseCurrentTab], [ctrl_shift, KeyCode::Char('1'), ActivateTab(0)], [ctrl_shift, KeyCode::Char('2'), ActivateTab(1)], [ctrl_shift, KeyCode::Char('3'), ActivateTab(2)], [ctrl_shift, KeyCode::Char('4'), ActivateTab(3)], [ctrl_shift, KeyCode::Char('5'), ActivateTab(4)], [ctrl_shift, KeyCode::Char('6'), ActivateTab(5)], [ctrl_shift, KeyCode::Char('7'), ActivateTab(6)], [ctrl_shift, KeyCode::Char('8'), ActivateTab(7)], [ctrl_shift, KeyCode::Char('9'), ActivateTab(8)], [ctrl_shift, KeyCode::Char('W'), CloseCurrentTab], [ KeyModifiers::SUPER | KeyModifiers::SHIFT, KeyCode::Char('['), ActivateTabRelative(-1) ], [ KeyModifiers::SUPER | KeyModifiers::SHIFT, KeyCode::Char('{'), ActivateTabRelative(-1) ], [ KeyModifiers::SUPER | KeyModifiers::SHIFT, KeyCode::Char(']'), ActivateTabRelative(1) ], [ KeyModifiers::SUPER | KeyModifiers::SHIFT, KeyCode::Char('}'), ActivateTabRelative(1) ], [KeyModifiers::SUPER, KeyCode::Char('r'), ReloadConfiguration], [ctrl_shift, KeyCode::Char('R'), ReloadConfiguration], [ctrl_shift, KeyCode::PageUp, MoveTabRelative(-1)], [ctrl_shift, KeyCode::PageDown, MoveTabRelative(1)], [KeyModifiers::SHIFT, KeyCode::PageUp, ScrollByPage(-1)], [KeyModifiers::SHIFT, KeyCode::PageDown, ScrollByPage(1)], [KeyModifiers::ALT, KeyCode::Char('9'), ShowTabNavigator], ); #[cfg(target_os = "macos")] m!([KeyModifiers::SUPER, KeyCode::Char('h'), HideApplication],); Self(map) } pub fn lookup(&self, key: KeyCode, mods: KeyModifiers) -> Option<KeyAssignment> { self.0 .get(&(key.normalize_shift_to_upper_case(mods), mods)) .cloned() } }
use crate::config::configuration; use crate::mux::domain::DomainId; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::path::PathBuf; use term::{KeyCode, KeyModifiers}; #[derive(Debug, Clone, Deserialize, Serialize)] pub enum SpawnTabDomain { DefaultDomain, CurrentTabDomain, Domain(DomainId), DomainName(String), } impl Default for SpawnTabDomain { fn default() -> Self { Self::CurrentTabDomain } } #[derive(Default, Debug, Clone, Deserialize, Serialize)] pub struct SpawnCommand { pub label: Option<String>, pub args: Option<Vec<String>>, pub cwd: Option<PathBuf>, #[serde(default)] pub set_environment_variables: HashMap<String, String>, #[serde(default)] pub domain: SpawnTabDomain, } #[derive(Debug, Clone, Deserialize, Serialize)] pub enum KeyAssignment { SpawnTab(SpawnTabDomain), SpawnWindow, ToggleFullScreen, Copy, Paste, ActivateTabRelative(isize), IncreaseFontSize, DecreaseFontSize, ResetFontSize, ActivateTab(usize), SendString(String), Nop, Hide, Show, CloseCurrentTab, ReloadConfiguration, MoveTabRelative(isize), MoveTab(usize), ScrollByPage(isize), ShowTabNavigator, HideApplication, QuitApplication, SpawnCommandInNewTab(SpawnCommand), SpawnCommandInNewWindow(SpawnCommand), ShowLauncher, } pub struct KeyMap(HashMap<(KeyCode, KeyModifiers), KeyAssignment>); impl KeyMap { pub fn new() -> Self { let mut map = configuration() .key_bindings() .expect("keys section of config to be valid"); macro_rules! m { ($([$mod:expr, $code:expr, $action:expr]),* $(,)?) => { $( map.entry(($code, $mod)).or_insert($action); )* }; }; use KeyAssignment::*; let ctrl_shift = KeyModifiers::CTRL | KeyModifiers::SHIFT; m!( [KeyModifiers::SHIFT, KeyCode::Insert, Paste], [KeyModifiers::SUPER, KeyCode::Char('c'), Copy], [KeyModifiers::SUPER, KeyCode::Char('v'), Paste], [ctrl_shift, KeyCode::Char('C'), Copy], [ctrl_shift, KeyCode::Char('V'), Paste], [KeyModifiers::ALT, KeyCode::Char('\n'), ToggleFullScreen], [KeyModifiers::ALT, KeyCode::Char('\r'), ToggleFullScreen], [KeyModifiers::ALT, KeyCode::Enter, ToggleFullScreen], [KeyModifiers::SUPER, KeyCode::Char('m'), Hide], [KeyModifiers::SUPER, KeyCode::Char('n'), SpawnWindow], [ctrl_shift, KeyCode::Char('M'), Hide], [ctrl_shift, KeyCode::Char('N'), SpawnWindow], [KeyModifiers::CTRL, KeyCode::Char('-'), DecreaseFontSize], [KeyModifiers::CTRL, KeyCode::Char('0'), ResetFontSize], [KeyModifiers::CTRL, KeyCode::Char('='), IncreaseFontSize], [KeyModifiers::SUPER, KeyCode::Char('-'), DecreaseFontSize], [KeyModifiers::SUPER, KeyCode::Char('0'), ResetFontSize], [KeyModifiers::SUPER, KeyCode::Char('='), IncreaseFontSize], [ KeyModifiers::SUPER, KeyCode::Char('t'), SpawnTab(SpawnTabDomain::CurrentTabDomain) ], [ ctrl_shift, KeyCode::Char('T'), SpawnTab(SpawnTabDomain::CurrentTabDomain) ], [ KeyModifiers::SUPER | KeyModifiers::SHIFT, KeyCode::Char('T'), SpawnTab(SpawnTabDomain::CurrentTabDomain) ], [KeyModifiers::SUPER, KeyCode::Char('1'), ActivateTab(0)], [KeyModifiers::SUPE
pub fn lookup(&self, key: KeyCode, mods: KeyModifiers) -> Option<KeyAssignment> { self.0 .get(&(key.normalize_shift_to_upper_case(mods), mods)) .cloned() } }
R, KeyCode::Char('2'), ActivateTab(1)], [KeyModifiers::SUPER, KeyCode::Char('3'), ActivateTab(2)], [KeyModifiers::SUPER, KeyCode::Char('4'), ActivateTab(3)], [KeyModifiers::SUPER, KeyCode::Char('5'), ActivateTab(4)], [KeyModifiers::SUPER, KeyCode::Char('6'), ActivateTab(5)], [KeyModifiers::SUPER, KeyCode::Char('7'), ActivateTab(6)], [KeyModifiers::SUPER, KeyCode::Char('8'), ActivateTab(7)], [KeyModifiers::SUPER, KeyCode::Char('9'), ActivateTab(8)], [KeyModifiers::SUPER, KeyCode::Char('w'), CloseCurrentTab], [ctrl_shift, KeyCode::Char('1'), ActivateTab(0)], [ctrl_shift, KeyCode::Char('2'), ActivateTab(1)], [ctrl_shift, KeyCode::Char('3'), ActivateTab(2)], [ctrl_shift, KeyCode::Char('4'), ActivateTab(3)], [ctrl_shift, KeyCode::Char('5'), ActivateTab(4)], [ctrl_shift, KeyCode::Char('6'), ActivateTab(5)], [ctrl_shift, KeyCode::Char('7'), ActivateTab(6)], [ctrl_shift, KeyCode::Char('8'), ActivateTab(7)], [ctrl_shift, KeyCode::Char('9'), ActivateTab(8)], [ctrl_shift, KeyCode::Char('W'), CloseCurrentTab], [ KeyModifiers::SUPER | KeyModifiers::SHIFT, KeyCode::Char('['), ActivateTabRelative(-1) ], [ KeyModifiers::SUPER | KeyModifiers::SHIFT, KeyCode::Char('{'), ActivateTabRelative(-1) ], [ KeyModifiers::SUPER | KeyModifiers::SHIFT, KeyCode::Char(']'), ActivateTabRelative(1) ], [ KeyModifiers::SUPER | KeyModifiers::SHIFT, KeyCode::Char('}'), ActivateTabRelative(1) ], [KeyModifiers::SUPER, KeyCode::Char('r'), ReloadConfiguration], [ctrl_shift, KeyCode::Char('R'), ReloadConfiguration], [ctrl_shift, KeyCode::PageUp, MoveTabRelative(-1)], [ctrl_shift, KeyCode::PageDown, MoveTabRelative(1)], [KeyModifiers::SHIFT, KeyCode::PageUp, ScrollByPage(-1)], [KeyModifiers::SHIFT, KeyCode::PageDown, ScrollByPage(1)], [KeyModifiers::ALT, KeyCode::Char('9'), ShowTabNavigator], ); #[cfg(target_os = "macos")] m!([KeyModifiers::SUPER, KeyCode::Char('h'), HideApplication],); Self(map) }
function_block-function_prefixed
[ { "content": "#[allow(dead_code)]\n\npub fn use_default_configuration() {\n\n CONFIG.use_defaults();\n\n}\n\n\n", "file_path": "src/config/mod.rs", "rank": 0, "score": 314081.53445833473 }, { "content": "fn default_term() -> String {\n\n \"xterm-256color\".into()\n\n}\n\n\n", "file...
Rust
src/console.rs
osenft/libtock-rs
55e498a4342ef7a56d1e78ac2d434a0c0e5f410d
use crate::callback::Identity0Consumer; use crate::executor; use crate::futures; use crate::result::TockResult; use crate::syscalls; use core::cell::Cell; use core::fmt; use core::fmt::Write; use core::mem; static mut CONSOLE: Option<Console> = None; const DRIVER_NUMBER: usize = 1; mod command_nr { pub const WRITE: usize = 1; } mod subscribe_nr { pub const SET_ALARM: usize = 1; } mod allow_nr { pub const SHARE_BUFFER: usize = 1; } #[non_exhaustive] pub struct ConsoleDriver; impl ConsoleDriver { pub fn create_console(self) { let console = Console { allow_buffer: [0; 64], }; console.set_global_console(); } } pub struct Console { allow_buffer: [u8; 64], } pub static mut MISSED_PRINT: bool = false; pub fn get_global_console() -> Option<Console> { unsafe { if let Some(con) = CONSOLE.take() { Some(con) } else { MISSED_PRINT = true; None } } } impl Console { pub fn write<S: AsRef<[u8]>>(&mut self, text: S) -> TockResult<()> { let mut not_written_yet = text.as_ref(); while !not_written_yet.is_empty() { let num_bytes_to_print = self.allow_buffer.len().min(not_written_yet.len()); self.allow_buffer[..num_bytes_to_print] .copy_from_slice(&not_written_yet[..num_bytes_to_print]); self.flush(num_bytes_to_print)?; not_written_yet = &not_written_yet[num_bytes_to_print..]; } Ok(()) } fn flush(&mut self, num_bytes_to_print: usize) -> TockResult<()> { let shared_memory = syscalls::allow( DRIVER_NUMBER, allow_nr::SHARE_BUFFER, &mut self.allow_buffer[..num_bytes_to_print], )?; let is_written = Cell::new(false); let mut is_written_alarm = || is_written.set(true); let subscription = syscalls::subscribe::<Identity0Consumer, _>( DRIVER_NUMBER, subscribe_nr::SET_ALARM, &mut is_written_alarm, )?; syscalls::command(DRIVER_NUMBER, command_nr::WRITE, num_bytes_to_print, 0)?; unsafe { executor::block_on(futures::wait_until(|| is_written.get())) }; mem::drop(subscription); mem::drop(shared_memory); Ok(()) } pub fn set_global_console(mut self) { unsafe { if MISSED_PRINT { let _ = write!(self, "A print was dropped while the console was locked"); MISSED_PRINT = false; } CONSOLE = Some(self); } } } impl fmt::Write for Console { fn write_str(&mut self, string: &str) -> Result<(), fmt::Error> { self.write(string).map_err(|_| fmt::Error) } } #[macro_export] macro_rules! println { () => ({ println!("") }); ($msg:expr) => ({ if let Some(mut console) = $crate::console::get_global_console() { use core::fmt::Write; let _ = writeln!(console, $msg); console.set_global_console(); } }); ($fmt:expr, $($arg:tt)+) => ({ if let Some(mut console) = $crate::console::get_global_console() { use core::fmt::Write; let _ = writeln!(console, "{}", format_args!($fmt, $($arg)+)); console.set_global_console(); } }); } #[macro_export] macro_rules! print { () => ({ print!("") }); ($msg:expr) => ({ if let Some(mut console) = $crate::console::get_global_console() { use core::fmt::Write; let _ = write!(console, $msg); console.set_global_console(); } }); ($fmt:expr, $($arg:tt)+) => ({ if let Some(mut console) = $crate::console::get_global_console() { use core::fmt::Write; let _ = write!(console, "{}", format_args!($fmt, $($arg)+)); console.set_global_console(); } }); }
use crate::callback::Identity0Consumer; use crate::executor; use crate::futures; use crate::result::TockResult; use crate::syscalls; use core::cell::Cell; use core::fmt; use core::fmt::Write; use core::mem; static mut CONSOLE: Option<Console> = None; const DRIVER_NUMBER: usize = 1; mod command_nr { pub const WRITE: usize = 1; } mod subscribe_nr { pub const SET_ALARM: usize = 1; } mod allow_nr { pub const SHARE_BUFFER: usize = 1; } #[non_exhaustive] pub struct ConsoleDriver; impl ConsoleDriver { pub fn create_console(self) { let console = Console { allow_buffer: [0; 64], }; console.set_global_console(); } } pub struct Console { allow_buffer: [u8; 64], } pub static mut MISSED_PRINT: bool = false; pu
impl Console { pub fn write<S: AsRef<[u8]>>(&mut self, text: S) -> TockResult<()> { let mut not_written_yet = text.as_ref(); while !not_written_yet.is_empty() { let num_bytes_to_print = self.allow_buffer.len().min(not_written_yet.len()); self.allow_buffer[..num_bytes_to_print] .copy_from_slice(&not_written_yet[..num_bytes_to_print]); self.flush(num_bytes_to_print)?; not_written_yet = &not_written_yet[num_bytes_to_print..]; } Ok(()) } fn flush(&mut self, num_bytes_to_print: usize) -> TockResult<()> { let shared_memory = syscalls::allow( DRIVER_NUMBER, allow_nr::SHARE_BUFFER, &mut self.allow_buffer[..num_bytes_to_print], )?; let is_written = Cell::new(false); let mut is_written_alarm = || is_written.set(true); let subscription = syscalls::subscribe::<Identity0Consumer, _>( DRIVER_NUMBER, subscribe_nr::SET_ALARM, &mut is_written_alarm, )?; syscalls::command(DRIVER_NUMBER, command_nr::WRITE, num_bytes_to_print, 0)?; unsafe { executor::block_on(futures::wait_until(|| is_written.get())) }; mem::drop(subscription); mem::drop(shared_memory); Ok(()) } pub fn set_global_console(mut self) { unsafe { if MISSED_PRINT { let _ = write!(self, "A print was dropped while the console was locked"); MISSED_PRINT = false; } CONSOLE = Some(self); } } } impl fmt::Write for Console { fn write_str(&mut self, string: &str) -> Result<(), fmt::Error> { self.write(string).map_err(|_| fmt::Error) } } #[macro_export] macro_rules! println { () => ({ println!("") }); ($msg:expr) => ({ if let Some(mut console) = $crate::console::get_global_console() { use core::fmt::Write; let _ = writeln!(console, $msg); console.set_global_console(); } }); ($fmt:expr, $($arg:tt)+) => ({ if let Some(mut console) = $crate::console::get_global_console() { use core::fmt::Write; let _ = writeln!(console, "{}", format_args!($fmt, $($arg)+)); console.set_global_console(); } }); } #[macro_export] macro_rules! print { () => ({ print!("") }); ($msg:expr) => ({ if let Some(mut console) = $crate::console::get_global_console() { use core::fmt::Write; let _ = write!(console, $msg); console.set_global_console(); } }); ($fmt:expr, $($arg:tt)+) => ({ if let Some(mut console) = $crate::console::get_global_console() { use core::fmt::Write; let _ = write!(console, "{}", format_args!($fmt, $($arg)+)); console.set_global_console(); } }); }
b fn get_global_console() -> Option<Console> { unsafe { if let Some(con) = CONSOLE.take() { Some(con) } else { MISSED_PRINT = true; None } } }
function_block-function_prefixed
[ { "content": "fn write_as_hex(buffer: &mut [u8], value: usize) {\n\n write_formatted(buffer, value, 0x10_00_00_00, 0x10);\n\n}\n\n\n", "file_path": "src/debug/mod.rs", "rank": 0, "score": 260874.68899420756 }, { "content": "fn hex(mut n: usize, buf: &mut [u8]) -> usize {\n\n let mut i ...
Rust
src/run/parser/portal2_live_timer.rs
AntyMew/livesplit-core
b59a45ddd85c914121d279df38ad5b0e581bd512
use std::io::{self, BufRead}; use std::result::Result as StdResult; use std::num::ParseFloatError; use {GameTime, Run, Segment, TimeSpan}; quick_error! { #[derive(Debug)] pub enum Error { ExpectedMap {} ExpectedMapName {} ExpectedDifferentMapName {} ExpectedStartTicks {} ExpectedEndTicks {} Ticks(err: ParseFloatError) { from() } Io(err: io::Error) { from() } } } pub type Result<T> = StdResult<T, Error>; static CHAPTERS: [(&str, &[&str]); 9] = [ ( "Chapter 1 - The Courtesy Call", &[ "sp_a1_intro1", "sp_a1_intro2", "sp_a1_intro3", "sp_a1_intro4", "sp_a1_intro5", "sp_a1_intro6", "sp_a1_intro7", "sp_a1_wakeup", "sp_a2_intro", ], ), ( "Chapter 2 - The Cold Boot", &[ "sp_a2_laser_intro", "sp_a2_laser_stairs", "sp_a2_dual_lasers", "sp_a2_laser_over_goo", "sp_a2_catapult_intro", "sp_a2_trust_fling", "sp_a2_pit_flings", "sp_a2_fizzler_intro", ], ), ( "Chapter 3 - The Return", &[ "sp_a2_sphere_peek", "sp_a2_ricochet", "sp_a2_bridge_intro", "sp_a2_bridge_the_gap", "sp_a2_laser_relays", "sp_a2_turret_intro", "sp_a2_turret_blocker", "sp_a2_laser_vs_turret", "sp_a2_pull_the_rug", ], ), ( "Chapter 4 - The Surprise", &[ "sp_a2_column_blocker", "sp_a2_laser_chaining", "sp_a2_triple_laser", "sp_a2_bts1", "sp_a2_bts2", ], ), ( "Chapter 5 - The Escape", &[ "sp_a2_bts3", "sp_a2_bts4", "sp_a2_bts5", "sp_a2_bts6", "sp_a2_core", ], ), ( "Chapter 6 - The Fall", &[ "sp_a3_00", "sp_a3_01", "sp_a3_03", "sp_a3_jump_intro", "sp_a3_bomb_flings", "sp_a3_crazy_box", "sp_a3_transition01", ], ), ( "Chapter 7 - The Reunion", &[ "sp_a3_speed_ramp", "sp_a3_speed_flings", "sp_a3_speed_flings", "sp_a3_speed_flings", "sp_a3_portal_intro", "sp_a3_end", ], ), ( "Chapter 8 - The Itch", &[ "sp_a4_intro", "sp_a4_tb_intro", "sp_a4_tb_trust_drop", "sp_a4_tb_wall_button", "sp_a4_tb_polarity", "sp_a4_tb_catch", "sp_a4_stop_the_box", "sp_a4_laser_catapult", "sp_a4_laser_platform", "sp_a4_speed_tb_catch", "sp_a4_jump_polarity", "sp_a4_jump_polarity", ], ), ( "Chapter 9 - The Part Where...", &[ "sp_a4_finale1", "sp_a4_finale2", "sp_a4_finale3", "sp_a4_finale4", ], ), ]; pub fn parse<R: BufRead>(source: R) -> Result<Run> { let mut run = Run::new(); run.set_game_name("Portal 2"); run.set_category_name("Any%"); let mut lines = source.lines().peekable(); lines.next(); let mut aggregate_ticks = 0.0; for &(chapter_name, maps) in &CHAPTERS { for &map in maps { let line = lines.next().ok_or(Error::ExpectedMap)??; let mut splits = line.split(','); let map_name = splits.next().ok_or(Error::ExpectedMapName)?; if map_name != map { return Err(Error::ExpectedDifferentMapName); } let start_ticks: f64 = splits.next().ok_or(Error::ExpectedStartTicks)?.parse()?; let end_ticks: f64 = splits.next().ok_or(Error::ExpectedEndTicks)?.parse()?; let map_ticks = end_ticks - start_ticks; aggregate_ticks += map_ticks; } let time = GameTime(Some(TimeSpan::from_seconds(aggregate_ticks / 60.0))).into(); let mut segment = Segment::new(chapter_name); segment.set_personal_best_split_time(time); run.push_segment(segment); } Ok(run) }
use std::io::{self, BufRead}; use std::result::Result as StdResult; use std::num::ParseFloatError; use {GameTime, Run, Segment, TimeSpan}; quick_error! { #[derive(Debug)] pub enum Error { ExpectedMap {} ExpectedMapName {} ExpectedDifferentMapName {} ExpectedStartTicks {} ExpectedEndTicks {} Ticks(err: ParseFloatError) { from() } Io(err: io::Error) { from() } } } pub type Result<T> = StdResult<T, Error>; static CHAPTERS: [(&str, &[&str]); 9] = [ ( "Chapter 1 - The Courtesy Call", &[ "sp_a1_intro1", "sp_a1_intro2", "sp_a1_intro3", "sp_a1_intro4", "sp_a1_intro5", "sp_a1_intro6", "sp_a1_intro7", "sp_a1_wakeup", "sp_a2_intro", ], ), ( "Chapter 2 - The Cold Boot", &[ "sp_a2_laser_intro", "sp_a2_laser_stairs", "sp_a2_dual_lasers", "sp_a2_laser_over_goo", "sp_a2_catapult_intro", "sp_a2_trust_fling", "sp_a2_pit_flings", "sp_a2_fizzler_intro", ], ), ( "Chapter 3 - The Return", &[ "sp_a2_sphere_peek", "sp_a2_ricochet", "sp_a2_bridge_intro", "sp_a2_bridge_the_gap", "sp_a2_laser_relays", "sp_a2_turret_intro", "sp_a2_turret_blocker", "sp_a2_laser_vs_turret", "sp_a2_pull_the_rug", ], ), ( "Chapter 4 - The Surprise", &[ "sp_a2_column_blocker", "sp_a2_laser_chaining", "sp_a2_triple_laser", "sp_a2_bts1", "sp_a2_bts2", ], ), ( "Chapter 5 - The Escape", &[ "sp_a2_bts3", "sp_a2_bts4", "sp_a2_bts5", "sp_a2_bts6", "sp_a2_core", ], ), ( "Chapter 6 - The Fall", &[ "sp_a3_00", "sp_a3_01", "sp_a3_03", "sp_a3_jump_intro", "sp_a3_bomb_flings", "sp_a3_crazy_box", "sp_a3_transition01", ], ), ( "Chapter 7 - The Reunion", &[ "sp_a3_speed_ramp", "sp_a3_speed_flings", "sp_a3_speed_flings", "sp_a3_speed_flings", "sp_a3_portal_intro", "sp_a3_end", ], ), ( "Chapter 8 - The Itch", &[ "sp_a4_intro", "sp_a4_tb_intro", "sp_a4_tb_trust_drop", "sp_a4_tb_wall_button", "sp_a4_tb_polarity", "sp_a4_tb_catch", "sp_a4_stop_the_box", "sp_a4_laser_catapult", "sp_a4_laser_platform", "sp_a4_speed_tb_catch", "sp_a4_jump_polarity", "sp_a4_jump_polarity", ], ), ( "Chapter 9 - The Part Where...", &[ "sp_a4_finale1", "sp_a4_finale2", "sp_a4_finale3", "sp_a4_finale4", ], ), ]; pub fn parse<R: BufRead>(source: R) -> Result<Run> { let mut run = Run::new(); run.set_game_name("Portal 2"); run.set_category_name("Any%"); let mut lines = source.lines().peekable(); lines.next(); let mut aggregate_ticks = 0.0; for &(chapter_name, maps) in &CHAPTERS { for &map in maps { let line = lines.next().ok_or(Error::ExpectedMap)??; let mut splits = line.split(','); let map_name = s
plits.next().ok_or(Error::ExpectedMapName)?; if map_name != map { return Err(Error::ExpectedDifferentMapName); } let start_ticks: f64 = splits.next().ok_or(Error::ExpectedStartTicks)?.parse()?; let end_ticks: f64 = splits.next().ok_or(Error::ExpectedEndTicks)?.parse()?; let map_ticks = end_ticks - start_ticks; aggregate_ticks += map_ticks; } let time = GameTime(Some(TimeSpan::from_seconds(aggregate_ticks / 60.0))).into(); let mut segment = Segment::new(chapter_name); segment.set_personal_best_split_time(time); run.push_segment(segment); } Ok(run) }
function_block-function_prefixed
[ { "content": "/// Attempts to parse a ShitSplit splits file.\n\npub fn parse<R: BufRead>(source: R) -> Result<Run> {\n\n let mut run = Run::new();\n\n\n\n let mut lines = source.lines();\n\n\n\n let line = lines.next().ok_or(Error::Empty)??;\n\n let mut splits = line.split('|');\n\n let category_...
Rust
warcio/src/record.rs
tari/warcdedupe
e33747e0804965837223c7bc2bca837bf8710aec
use std::cmp; use std::error::Error as StdError; use std::fmt; use std::io::prelude::*; use std::io::Error as IoError; use std::ops::Drop; use buf_redux::BufReader; pub use buf_redux::Buffer; use thiserror::Error; use crate::compression::{self, Compression}; use crate::header::get_record_header; use crate::{FieldName, Header}; use super::HeaderParseError; const SKIP_BUF_LEN: usize = 4096; #[derive(Debug, Error)] pub enum InvalidRecord { #[error("record header is not valid: {0}")] InvalidHeader(#[source] HeaderParseError), #[error("Content-Length is not a valid integer (contained bytes {0:?})")] UnknownLength(Option<Vec<u8>>), #[error("unexpected end of input")] EndOfStream, #[error("I/O error")] IoError(#[source] IoError), } impl From<HeaderParseError> for InvalidRecord { fn from(e: HeaderParseError) -> Self { match e { HeaderParseError::IoError(e) => InvalidRecord::IoError(e), HeaderParseError::Truncated => InvalidRecord::EndOfStream, e => InvalidRecord::InvalidHeader(e), } } } #[derive(Debug)] enum Input<R> where R: BufRead, { Plain(R, Buffer), Compressed(BufReader<flate2::bufread::GzDecoder<R>>), } impl<R> Input<R> where R: BufRead, { fn into_inner(self) -> (R, Buffer) { match self { Input::Plain(r, buf) => (r, buf), Input::Compressed(r) => { let (r, buf) = r.into_inner_with_buffer(); (r.into_inner(), buf) } } } } impl<R> Read for Input<R> where R: BufRead, { fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { match self { Input::Plain(r, _) => r.read(buf), Input::Compressed(r) => r.read(buf), } } } impl<R> BufRead for Input<R> where R: BufRead, { fn fill_buf(&mut self) -> std::io::Result<&[u8]> { match self { Input::Plain(r, _) => r.fill_buf(), Input::Compressed(r) => r.fill_buf(), } } fn consume(&mut self, amt: usize) { match self { Input::Plain(r, _) => r.consume(amt), Input::Compressed(r) => r.consume(amt), } } } #[derive(Debug)] pub struct Record<R> where R: BufRead, { pub header: crate::header::Header, content_length: u64, bytes_remaining: u64, input: Input<R>, debug_info: DebugInfo, } #[cfg(debug_assertions)] #[derive(Clone, Debug, PartialEq, Eq)] struct DebugInfo { consumed_tail: bool, } #[cfg(not(debug_assertions))] #[derive(Clone, Debug, PartialEq, Eq)] struct DebugInfo; impl DebugInfo { #[cfg(debug_assertions)] fn new() -> DebugInfo { DebugInfo { consumed_tail: false, } } #[cfg(debug_assertions)] fn set_consumed_tail(&mut self) { debug_assert!(!self.consumed_tail, "Record tail was already consumed!"); self.consumed_tail = true; } #[cfg(not(debug_assertions))] fn new() -> DebugInfo { DebugInfo } #[cfg(not(debug_assertions))] fn set_consumed_tail(&mut self) {} } impl<R> Read for Record<R> where R: BufRead, { fn read(&mut self, buf: &mut [u8]) -> Result<usize, IoError> { let constrained = if (buf.len() as u64) > self.bytes_remaining { &mut buf[..self.bytes_remaining as usize] } else { buf }; let n = self.input.read(constrained)?; self.bytes_remaining -= n as u64; Ok(n) } } impl<R> BufRead for Record<R> where R: BufRead, { fn fill_buf(&mut self) -> Result<&[u8], IoError> { let buf = self.input.fill_buf()?; let remaining = self.bytes_remaining as usize; let out = if buf.len() > remaining { &buf[..remaining] } else { buf }; debug_assert!(out.len() <= remaining); Ok(out) } fn consume(&mut self, n: usize) { debug_assert!(n <= self.bytes_remaining as usize); self.input.consume(n); self.bytes_remaining -= n as u64; } } #[derive(Debug)] pub enum FinishError { MissingTail, Io(IoError), } impl From<IoError> for FinishError { fn from(e: IoError) -> FinishError { FinishError::Io(e) } } impl fmt::Display for FinishError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "Error closing WARC record: ")?; match self { FinishError::Io(ref e) => write!(f, "I/O error: {}", e), FinishError::MissingTail => write!(f, "missing record tail"), } } } impl StdError for FinishError { fn cause(&self) -> Option<&dyn StdError> { if let FinishError::Io(e) = self { Some(e) } else { None } } } impl<R> Record<R> where R: BufRead, { pub fn read_from(reader: R, compression: Compression) -> Result<Self, InvalidRecord> { let buffer = Buffer::with_capacity(8 << 10); Self::read_buffered_from(reader, buffer, compression) } pub fn read_buffered_from( reader: R, mut buffer: Buffer, compression: Compression, ) -> Result<Self, InvalidRecord> { let mut input = match compression { Compression::None => Input::Plain(reader, buffer), Compression::Gzip => { buffer.clear(); Input::Compressed(BufReader::with_buffer( buffer, flate2::bufread::GzDecoder::new(reader), )) } }; let header = get_record_header(&mut input)?; let len = match header.content_length_lenient() { None => { return Err(InvalidRecord::UnknownLength( header .get_field_bytes("Content-Length") .map(|bytes| bytes.to_vec()), )); } Some(n) => n, }; let record = Record { content_length: len, bytes_remaining: len, header, input, debug_info: DebugInfo::new(), }; Ok(record) } #[allow(clippy::len_without_is_empty)] pub fn len(&self) -> u64 { self.content_length } pub fn finish(mut self) -> Result<(R, Buffer), FinishError> { self.finish_internal()?; let Record { input, .. } = self; Ok(input.into_inner()) } fn finish_internal(&mut self) -> Result<(), FinishError> { let mut buf = [0u8; SKIP_BUF_LEN]; let mut remaining = self.bytes_remaining; while remaining > 0 { let n = cmp::min(buf.len(), remaining as usize); self.input.read_exact(&mut buf[..n])?; remaining -= n as u64; } self.debug_info.set_consumed_tail(); { let mut buf = [0u8; 4]; if let Err(e) = self.input.read_exact(&mut buf[..]) { if e.kind() == ::std::io::ErrorKind::UnexpectedEof { return Err(FinishError::MissingTail); } return Err(e.into()); } if &buf[..] != b"\r\n\r\n" { return Err(FinishError::MissingTail); } } if let Input::Compressed(ref mut input) = self.input { loop { let n = input.fill_buf()?.len(); if n == 0 { break; } trace!( "compressed record finish consuming {} extra bytes", buf.len() ); input.consume(n); } } Ok(()) } } pub struct RecordWriter<W: Write> { limit: u64, written: u64, writer: compression::Writer<W>, finished: bool, } impl<W: Write> RecordWriter<W> { pub fn new(dest: W, header: &Header, compression: Compression) -> std::io::Result<Self> { let mut dest = compression::Writer::new(dest, compression); write!(&mut dest, "WARC/{}\r\n", header.version())?; for (key, value) in header.iter_field_bytes() { write!(&mut dest, "{}: ", <FieldName as AsRef<str>>::as_ref(key))?; dest.write_all(value)?; write!(&mut dest, "\r\n")?; } write!(&mut dest, "\r\n")?; Ok(RecordWriter { limit: header.content_length(), writer: dest, written: 0, finished: false, }) } } impl<W: Write> Write for RecordWriter<W> { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { debug_assert!(self.written <= self.limit); let take = std::cmp::min(buf.len() as u64, self.limit - self.written); let written = self.writer.write(&buf[..take as usize])?; self.written += written as u64; if self.written == self.limit && !self.finished { self.writer.write_all(b"\r\n\r\n")?; self.finished = true; } Ok(written) } fn flush(&mut self) -> std::io::Result<()> { self.writer.flush() } } impl<W: Write> Drop for RecordWriter<W> { fn drop(&mut self) { if self.written < self.limit { error!( "record contents wrote only {} bytes but expected {}", self.written, self.limit ); } } } pub struct RecordReader<R> where R: BufRead { input: R, compression: Compression, } impl<R: BufRead> RecordReader<R> { pub fn new(input: R, compression: Compression) -> Self { RecordReader { input, compression } } pub fn next(&mut self) -> Option<Result<Record<&mut R>, InvalidRecord>> { if self.input.fill_buf().map_or(false, |b| b.is_empty()) { None } else { Some(Record::read_from(&mut self.input, self.compression)) } } }
use std::cmp; use std::error::Error as StdError; use std::fmt; use std::io::prelude::*; use std::io::Error as IoError; use std::ops::Drop; use buf_redux::BufReader; pub use buf_redux::Buffer; use thiserror::Error; use crate::compression::{self, Compression}; use crate::header::get_record_header; use crate::{FieldName, Header}; use super::HeaderParseError; const SKIP_BUF_LEN: usize = 4096; #[derive(Debug, Error)] pub enum InvalidRecord { #[error("record header is not valid: {0}")] InvalidHeader(#[source] HeaderParseError), #[error("Content-Length is not a valid integer (contained bytes {0:?})")] UnknownLength(Option<Vec<u8>>), #[error("unexpected end of input")] EndOfStream, #[error("I/O error")] IoError(#[source] IoError), } impl From<HeaderParseError> for InvalidRecord { fn from(e: HeaderParseError) -> Self { match e { HeaderParseError::IoError(e) => InvalidRecord::IoError(e), HeaderParseError::Truncated => InvalidRecord::EndOfStream, e => InvalidRecord::InvalidHeader(e), } } } #[derive(Debug)] enum Input<R> where R: BufRead, { Plain(R, Buffer), Compressed(BufReader<flate2::bufread::GzDecoder<R>>), } impl<R> Input<R> where R: BufRead, { fn into_inner(self) -> (R, Buffer) { match self { Input::Plain(r, buf) => (r, buf), Input::Compressed(r) => { let (r, buf) = r.into_inner_with_buffer(); (r.into_inner(), buf) } } } } impl<R> Read for Input<R> where R: BufRead, { fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { match self { Input::Plain(r, _) => r.read(buf), Input::Compressed(r) => r.read(buf), } } } impl<R> BufRead for Input<R> where R: BufRead, { fn fill_buf(&mut self) -> std::io::Result<&[u8]> { match self { Input::Plain(r, _) => r.fill_buf(), Input::Compressed(r) => r.fill_buf(), } } fn consume(&mut self, amt: usize) { match self { Input::Plain(r, _) => r.consume(amt), Input::Compressed(r) => r.consume(amt), } } } #[derive(Debug)] pub struct Record<R> where R: BufRead, { pub header: crate::header::Header, content_length: u64, bytes_remaining: u64, input: Input<R>, debug_info: DebugInfo, } #[cfg(debug_assertions)] #[derive(Clone, Debug, PartialEq, Eq)] struct DebugInfo { consumed_tail: bool, } #[cfg(not(debug_assertions))] #[derive(Clone, Debug, PartialEq, Eq)] struct DebugInfo; impl DebugInfo { #[cfg(debug_assertions)] fn new() -> DebugInfo { DebugInfo { consumed_tail: false, } } #[cfg(debug_assertions)] fn set_consumed_tail(&mut self) { debug_assert!(!self.consumed_tail, "Record tail was already consumed!"); self.consumed_tail = true; } #[cfg(not(debug_assertions))] fn new() -> DebugInfo { DebugInfo } #[cfg(not(debug_assertions))] fn set_consumed_tail(&mut self) {} } impl<R> Read for Record<R> where R: BufRead, { fn read(&mut self, buf: &mut [u8]) -> Result<usize, IoError> { let constrained = if (buf.len() as u64) > self.bytes_remaining { &mut buf[..self.bytes_remaining as usize] } else { buf }; let n = self.input.read(constrained)?; self.bytes_remaining -= n as u64; Ok(n) } } impl<R> BufRead for Record<R> where R: BufRead, { fn fill_buf(&mut self) -> Result<&[u8], IoError> { let buf = self.input.fill_buf()?; let remaining = self.bytes_remaining as usize; let out = if buf.len() > remaining { &buf[..remaining] } else { buf }; debug_assert!(out.len() <= remaining); Ok(out) } fn consume(&mut self, n: usize) { debug_assert!(n <= self.bytes_remaining as usize); self.input.consume(n); self.bytes_remaining -= n as u64; } } #[derive(Debug)] pub enum FinishError { MissingTail, Io(IoError), } impl From<IoError> for FinishError { fn from(e: IoError) -> FinishError { FinishError::Io(e) } } impl fmt::Display for FinishError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "Error closing WARC record: ")?; match self { FinishError::Io(ref e) => write!(f, "I/O error: {}", e), FinishError::MissingTail => write!(f, "missing record tail"), } } } impl StdError for FinishError { fn cause(&self) -> Option<&dyn StdError> { if let FinishError::Io(e) = self { Some(e) } else { None } } } impl<R> Record<R> where R: BufRead, { pub fn read_from(reader: R, compression: Compression) -> Result<Self, InvalidRecord> { let buffer = Buffer::with_capacity(8 << 10); Self::read_buffered_from(reader, buffer, compression) } pub fn read_buffered_from( reader: R, mut buffer: Buffer, compression: Compression, ) -> Result<Self, InvalidRecord> { let mut input = match compression { Compression::None => Input::Plain(reader, buffer), Compression::Gzip => { buffer.clear(); Input::Compressed(BufReader::with_buffer( buffer, flate2::bufread::GzDecoder::new(reader), )) } }; let header = get_record_header(&mut input)?; let len = match header.content_length_lenient() { None => { return
; } Some(n) => n, }; let record = Record { content_length: len, bytes_remaining: len, header, input, debug_info: DebugInfo::new(), }; Ok(record) } #[allow(clippy::len_without_is_empty)] pub fn len(&self) -> u64 { self.content_length } pub fn finish(mut self) -> Result<(R, Buffer), FinishError> { self.finish_internal()?; let Record { input, .. } = self; Ok(input.into_inner()) } fn finish_internal(&mut self) -> Result<(), FinishError> { let mut buf = [0u8; SKIP_BUF_LEN]; let mut remaining = self.bytes_remaining; while remaining > 0 { let n = cmp::min(buf.len(), remaining as usize); self.input.read_exact(&mut buf[..n])?; remaining -= n as u64; } self.debug_info.set_consumed_tail(); { let mut buf = [0u8; 4]; if let Err(e) = self.input.read_exact(&mut buf[..]) { if e.kind() == ::std::io::ErrorKind::UnexpectedEof { return Err(FinishError::MissingTail); } return Err(e.into()); } if &buf[..] != b"\r\n\r\n" { return Err(FinishError::MissingTail); } } if let Input::Compressed(ref mut input) = self.input { loop { let n = input.fill_buf()?.len(); if n == 0 { break; } trace!( "compressed record finish consuming {} extra bytes", buf.len() ); input.consume(n); } } Ok(()) } } pub struct RecordWriter<W: Write> { limit: u64, written: u64, writer: compression::Writer<W>, finished: bool, } impl<W: Write> RecordWriter<W> { pub fn new(dest: W, header: &Header, compression: Compression) -> std::io::Result<Self> { let mut dest = compression::Writer::new(dest, compression); write!(&mut dest, "WARC/{}\r\n", header.version())?; for (key, value) in header.iter_field_bytes() { write!(&mut dest, "{}: ", <FieldName as AsRef<str>>::as_ref(key))?; dest.write_all(value)?; write!(&mut dest, "\r\n")?; } write!(&mut dest, "\r\n")?; Ok(RecordWriter { limit: header.content_length(), writer: dest, written: 0, finished: false, }) } } impl<W: Write> Write for RecordWriter<W> { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { debug_assert!(self.written <= self.limit); let take = std::cmp::min(buf.len() as u64, self.limit - self.written); let written = self.writer.write(&buf[..take as usize])?; self.written += written as u64; if self.written == self.limit && !self.finished { self.writer.write_all(b"\r\n\r\n")?; self.finished = true; } Ok(written) } fn flush(&mut self) -> std::io::Result<()> { self.writer.flush() } } impl<W: Write> Drop for RecordWriter<W> { fn drop(&mut self) { if self.written < self.limit { error!( "record contents wrote only {} bytes but expected {}", self.written, self.limit ); } } } pub struct RecordReader<R> where R: BufRead { input: R, compression: Compression, } impl<R: BufRead> RecordReader<R> { pub fn new(input: R, compression: Compression) -> Self { RecordReader { input, compression } } pub fn next(&mut self) -> Option<Result<Record<&mut R>, InvalidRecord>> { if self.input.fill_buf().map_or(false, |b| b.is_empty()) { None } else { Some(Record::read_from(&mut self.input, self.compression)) } } }
Err(InvalidRecord::UnknownLength( header .get_field_bytes("Content-Length") .map(|bytes| bytes.to_vec()), ))
call_expression
[ { "content": "fn run_with_progress<R: std::io::BufRead + std::io::Seek, D, L, W>(\n\n enable: bool,\n\n mut deduplicator: Deduplicator<D, L, W>,\n\n mut input: R,\n\n input_compression: Compression,\n\n) -> Result<(u64, u64), ProcessError>\n\nwhere\n\n R: std::io::BufRead + std::io::Seek,\n\n ...
Rust
contracts/q_native/src/contract/handler/token.rs
quasar-protocol/quasar-cosmwasm
3849c83f2057998637c2c32bcebfe535fd47d4a3
use cosmwasm_std::{ log, Api, Binary, CanonicalAddr, Env, Extern, HandleResponse, HumanAddr, InitResponse, Querier, ReadonlyStorage, StdError, StdResult, Storage, Uint128, }; use cosmwasm_storage::{PrefixedStorage, ReadonlyPrefixedStorage}; use crate::state::{ bytes_to_u128, get_allowance, get_balance, set_allowance, to_u128, ALLOWANCE_PREFIX, BALANCE_PREFIX, }; pub fn try_transfer<S: Storage, A: Api, Q: Querier>( deps: &mut Extern<S, A, Q>, env: Env, recipient: &HumanAddr, amount: &Uint128, ) -> StdResult<HandleResponse> { let sender_address_raw = deps.api.canonical_address(recipient)?; let recipient_address_raw = deps.api.canonical_address(recipient)?; let amount_raw = amount.u128(); perform_transfer( &mut deps.storage, &sender_address_raw, &recipient_address_raw, amount_raw, )?; let res = HandleResponse { messages: vec![], log: vec![ log("action", "transfer"), log("sender", env.message.sender.as_str()), log("recipient", recipient.as_str()), ], data: None, }; Ok(res) } pub fn try_transfer_from<S: Storage, A: Api, Q: Querier>( deps: &mut Extern<S, A, Q>, env: Env, owner: &HumanAddr, recipient: &HumanAddr, amount: &Uint128, ) -> StdResult<HandleResponse> { let spender_address_raw = deps.api.canonical_address(&env.message.sender)?; let owner_address_raw = deps.api.canonical_address(owner)?; let recipient_address_raw = deps.api.canonical_address(recipient)?; let amount_raw = amount.u128(); let mut allowance = get_allowance(&deps.storage, &owner_address_raw, &spender_address_raw)?; if allowance < amount_raw { return Err(StdError::generic_err(format!( "Insufficient allowance: allowance={}, required={}", allowance, amount_raw ))); } allowance -= amount_raw; set_allowance( &mut deps.storage, &owner_address_raw, &spender_address_raw, allowance, )?; perform_transfer( &mut deps.storage, &owner_address_raw, &recipient_address_raw, amount_raw, )?; let res = HandleResponse { messages: vec![], log: vec![ log("action", "transfer_from"), log("spender", env.message.sender.as_str()), log("sender", owner.as_str()), log("recipient", recipient.as_str()), ], data: None, }; Ok(res) } pub fn try_approve<S: Storage, A: Api, Q: Querier>( deps: &mut Extern<S, A, Q>, env: Env, spender: &HumanAddr, amount: &Uint128, ) -> StdResult<HandleResponse> { let owner_address_raw = deps.api.canonical_address(&env.message.sender)?; let spender_address_raw = deps.api.canonical_address(spender)?; set_allowance( &mut deps.storage, &owner_address_raw, &spender_address_raw, amount.u128(), )?; let res = HandleResponse { messages: vec![], log: vec![ log("action", "approve"), log("owner", env.message.sender.as_str()), log("spender", spender.as_str()), ], data: None, }; Ok(res) } fn perform_transfer<T: Storage>( store: &mut T, from: &CanonicalAddr, to: &CanonicalAddr, amount: u128, ) -> StdResult<()> { let mut balances_store = PrefixedStorage::new(BALANCE_PREFIX, store); let mut from_balance = to_u128(&balances_store, from.as_slice())?; if from_balance < amount { return Err(StdError::generic_err(format!( "Insufficient funds: sender={}, balance={}, required={}", HumanAddr::from(from.to_string()), from_balance, amount ))); } from_balance -= amount; balances_store.set(from.as_slice(), &from_balance.to_be_bytes()); let mut to_balance = to_u128(&balances_store, to.as_slice())?; to_balance += amount; balances_store.set(to.as_slice(), &to_balance.to_be_bytes()); Ok(()) } pub fn mint_tokens<T: Storage>( store: &mut T, to: &CanonicalAddr, amount: u128, ) -> StdResult<()> { let mut balances_store = PrefixedStorage::new(BALANCE_PREFIX, store); let mut to_balance = to_u128(&balances_store, to.as_slice())?; to_balance += amount; balances_store.set(to.as_slice(), &to_balance.to_be_bytes()); Ok(()) } pub fn burn_tokens<T: Storage>( store: &mut T, to: &CanonicalAddr, amount: u128, ) -> StdResult<()> { let mut balances_store = PrefixedStorage::new(BALANCE_PREFIX, store); let mut to_balance = to_u128(&balances_store, to.as_slice())?; to_balance -= amount; balances_store.set(to.as_slice(), &to_balance.to_be_bytes()); Ok(()) }
use cosmwasm_std::{ log, Api, Binary, CanonicalAddr, Env, Extern, HandleResponse, HumanAddr, InitResponse, Querier, ReadonlyStorage, StdError, StdResult, Storage, Uint128, }; use cosmwasm_storage::{PrefixedStorage, ReadonlyPrefixedStorage}; use crate::state::{ bytes_to_u128, get_allowance, get_balance, set_allowance, to_u128, ALLOWANCE_PREFIX, BALANCE_PREFIX, }; pub fn try_transfer<S: Storage, A: Api, Q: Querier>( deps: &mut Extern<S, A, Q>, env: Env, recipient: &HumanAddr, amount: &Uint128, ) -> StdResult<HandleResponse> { let sender_address_raw = deps.api.canonical_address(recipient)?; let recipient_address_raw = deps.api.canonical_address(recipient)?; let amount_raw = amount.u128(); perform_transfer( &mut deps.storage, &sender_address_raw, &recipient_address_raw, amount_raw, )?; let res = HandleResponse { messages: vec![], log: vec![ log("action", "transfer"), log("sender", env.message.sender.as_str()), log("recipient", recipient.as_str()), ], data: None, }; Ok(res) } pub fn try_transfer_from<S: Storage, A: Api, Q: Querier>( deps: &mut Extern<S, A, Q>, env: Env, owner: &HumanAddr, recipient: &HumanAddr, amount: &Uint128, ) -> StdResult<HandleResponse> { let spender_address_raw = deps.api.canonical_address(&env.message.sender)?; let owner_address_raw = deps.api.canonical_address(owner)?; let recipient_address_raw = deps.api.canonical_address(recipient)?; let amount_raw = amount.u128(); let mut allowance = get_allowance(&deps.storage, &owner_address_raw, &spender_address_raw)?; if allowance < amount_raw { return Err(StdError::generic_err(format!( "Insufficient allowance: allowance={}, required={}", allowance, amount_raw ))); } allowance -= amount_raw; set_allowance( &mut deps.storage, &owner_address_raw, &spender_address_raw, allowance, )?; perform_transfer( &mut deps.storage, &owner_address_raw, &recipient_address_raw, amount_raw, )?; let res = HandleResponse { messages: vec![], log: vec![ log("action", "transfer_from"), log("spender", env.message.sender.as_str()), log("sender", owner.as_str()), log("recipient", recipient.as_str()), ], data: None, }; Ok(res) } pub fn try_approve<S: Storage, A: Api, Q: Querier>( deps: &mut Extern<S, A, Q>, env: Env, spender: &HumanAddr, amount: &Uint128, ) -> StdResult<HandleResponse> { let owner_address_raw = deps.api.canonical_address(&env.message.sender)?; let spender_address_raw = deps.api.canonical_address(spender)?; set_allowance( &mut deps.storage, &owner_address_raw, &spender_address_raw, amount.u128(), )?; let res = HandleResponse { messages: vec![], log: vec![ log("action", "approve"), log("owner", env.message.sender.as_str()), log("spender", spender.as_str()), ], data: None, }; Ok(res) } fn perform_transfer<T: Storage>( store: &mut T,
nce.to_be_bytes()); Ok(()) } pub fn mint_tokens<T: Storage>( store: &mut T, to: &CanonicalAddr, amount: u128, ) -> StdResult<()> { let mut balances_store = PrefixedStorage::new(BALANCE_PREFIX, store); let mut to_balance = to_u128(&balances_store, to.as_slice())?; to_balance += amount; balances_store.set(to.as_slice(), &to_balance.to_be_bytes()); Ok(()) } pub fn burn_tokens<T: Storage>( store: &mut T, to: &CanonicalAddr, amount: u128, ) -> StdResult<()> { let mut balances_store = PrefixedStorage::new(BALANCE_PREFIX, store); let mut to_balance = to_u128(&balances_store, to.as_slice())?; to_balance -= amount; balances_store.set(to.as_slice(), &to_balance.to_be_bytes()); Ok(()) }
from: &CanonicalAddr, to: &CanonicalAddr, amount: u128, ) -> StdResult<()> { let mut balances_store = PrefixedStorage::new(BALANCE_PREFIX, store); let mut from_balance = to_u128(&balances_store, from.as_slice())?; if from_balance < amount { return Err(StdError::generic_err(format!( "Insufficient funds: sender={}, balance={}, required={}", HumanAddr::from(from.to_string()), from_balance, amount ))); } from_balance -= amount; balances_store.set(from.as_slice(), &from_balance.to_be_bytes()); let mut to_balance = to_u128(&balances_store, to.as_slice())?; to_balance += amount; balances_store.set(to.as_slice(), &to_bala
function_block-random_span
[ { "content": "fn accrue_interest<S: Storage, A: Api, Q: Querier>(deps: &mut Extern<S, A, Q>, env: Env) -> StdResult<()> {\n\n let prior_state = get_state(&deps.storage)?;\n\n\n\n let borrow_rate = get_borrow_rate(&prior_state.cash, &prior_state.total_borrows, &prior_state.total_reserves);\n\n\n\n if b...
Rust
nfe/src/base/totais.rs
fernandobatels/fiscal-rs
9c5856907dd1c4429dc256a41914676fc0cc5a70
use super::Error; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::str::FromStr; #[derive(Debug, PartialEq, Clone)] pub struct Totalizacao { pub valor_base_calculo: f32, pub valor_icms: f32, pub valor_produtos: f32, pub valor_frete: f32, pub valor_seguro: f32, pub valor_desconto: f32, pub valor_outros: f32, pub valor_pis: f32, pub valor_cofins: f32, pub valor_total: f32, pub valor_aproximado_tributos: f32, } impl FromStr for Totalizacao { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { quick_xml::de::from_str(s).map_err(|e| e.into()) } } impl ToString for Totalizacao { fn to_string(&self) -> String { quick_xml::se::to_string(self).expect("Falha ao serializar a totalização") } } impl Serialize for Totalizacao { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let icms = IcmsTot { valor_base_calculo: self.valor_base_calculo, valor_icms: self.valor_icms, valor_produtos: self.valor_produtos, valor_frete: self.valor_frete, valor_seguro: self.valor_seguro, valor_desconto: self.valor_desconto, valor_outros: self.valor_outros, valor_pis: self.valor_pis, valor_cofins: self.valor_cofins, valor_total: self.valor_total, valor_aproximado_tributos: self.valor_aproximado_tributos, }; let total = TotalContainer { icms }; total.serialize(serializer) } } impl<'de> Deserialize<'de> for Totalizacao { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let helper = TotalContainer::deserialize(deserializer)?; Ok(Totalizacao { valor_base_calculo: helper.icms.valor_base_calculo, valor_icms: helper.icms.valor_icms, valor_produtos: helper.icms.valor_produtos, valor_frete: helper.icms.valor_frete, valor_seguro: helper.icms.valor_seguro, valor_desconto: helper.icms.valor_desconto, valor_outros: helper.icms.valor_outros, valor_pis: helper.icms.valor_pis, valor_cofins: helper.icms.valor_cofins, valor_total: helper.icms.valor_total, valor_aproximado_tributos: helper.icms.valor_aproximado_tributos, }) } } #[derive(Deserialize, Serialize)] #[serde(rename = "total")] struct TotalContainer { #[serde(rename = "ICMSTot")] icms: IcmsTot, } #[derive(Deserialize, Serialize)] struct IcmsTot { #[serde(rename = "$unflatten=vBC")] valor_base_calculo: f32, #[serde(rename = "$unflatten=vICMS")] valor_icms: f32, #[serde(rename = "$unflatten=vProd")] valor_produtos: f32, #[serde(rename = "$unflatten=vFrete")] valor_frete: f32, #[serde(rename = "$unflatten=vSeg")] valor_seguro: f32, #[serde(rename = "$unflatten=vDesc")] valor_desconto: f32, #[serde(rename = "$unflatten=vOutro")] valor_outros: f32, #[serde(rename = "$unflatten=vPIS")] valor_pis: f32, #[serde(rename = "$unflatten=vCOFINS")] valor_cofins: f32, #[serde(rename = "$unflatten=vNF")] valor_total: f32, #[serde(rename = "$unflatten=vTotTrib")] valor_aproximado_tributos: f32, }
use super::Error; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::str::FromStr; #[derive(Debug, PartialEq, Clone)] pub struct Totalizacao { pub valor_base_calculo: f32, pub valor_icms: f32, pub valor_produtos: f32, pub valor_frete: f32, pub valor_seguro: f32, pub valor_desconto: f32, pub valor_outros: f32, pub valor_pis: f32, pub valor_cofins: f32, pub valor_total: f32, pub valor_aproximado_tributos: f32, } impl FromStr for Totalizacao { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { quick_xml::de::from_str(s).map_err(|e| e.into()) } } impl ToString for Totalizacao { fn to_string(&self) -> String { quick_xml::se::to_string(self).expect("Falha ao serializar a totalização") } } impl Serialize for Totalizacao {
} impl<'de> Deserialize<'de> for Totalizacao { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let helper = TotalContainer::deserialize(deserializer)?; Ok(Totalizacao { valor_base_calculo: helper.icms.valor_base_calculo, valor_icms: helper.icms.valor_icms, valor_produtos: helper.icms.valor_produtos, valor_frete: helper.icms.valor_frete, valor_seguro: helper.icms.valor_seguro, valor_desconto: helper.icms.valor_desconto, valor_outros: helper.icms.valor_outros, valor_pis: helper.icms.valor_pis, valor_cofins: helper.icms.valor_cofins, valor_total: helper.icms.valor_total, valor_aproximado_tributos: helper.icms.valor_aproximado_tributos, }) } } #[derive(Deserialize, Serialize)] #[serde(rename = "total")] struct TotalContainer { #[serde(rename = "ICMSTot")] icms: IcmsTot, } #[derive(Deserialize, Serialize)] struct IcmsTot { #[serde(rename = "$unflatten=vBC")] valor_base_calculo: f32, #[serde(rename = "$unflatten=vICMS")] valor_icms: f32, #[serde(rename = "$unflatten=vProd")] valor_produtos: f32, #[serde(rename = "$unflatten=vFrete")] valor_frete: f32, #[serde(rename = "$unflatten=vSeg")] valor_seguro: f32, #[serde(rename = "$unflatten=vDesc")] valor_desconto: f32, #[serde(rename = "$unflatten=vOutro")] valor_outros: f32, #[serde(rename = "$unflatten=vPIS")] valor_pis: f32, #[serde(rename = "$unflatten=vCOFINS")] valor_cofins: f32, #[serde(rename = "$unflatten=vNF")] valor_total: f32, #[serde(rename = "$unflatten=vTotTrib")] valor_aproximado_tributos: f32, }
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let icms = IcmsTot { valor_base_calculo: self.valor_base_calculo, valor_icms: self.valor_icms, valor_produtos: self.valor_produtos, valor_frete: self.valor_frete, valor_seguro: self.valor_seguro, valor_desconto: self.valor_desconto, valor_outros: self.valor_outros, valor_pis: self.valor_pis, valor_cofins: self.valor_cofins, valor_total: self.valor_total, valor_aproximado_tributos: self.valor_aproximado_tributos, }; let total = TotalContainer { icms }; total.serialize(serializer) }
function_block-full_function
[ { "content": "#[test]\n\nfn to_string() -> Result<(), Error> {\n\n let mut xml_original = \"<transp><modFrete>9</modFrete></transp>\".to_string();\n\n xml_original.retain(|c| c != '\\n' && c != ' ');\n\n\n\n let transporte = xml_original.parse::<Transporte>()?;\n\n let xml_novo = transporte.to_strin...
Rust
src/exmo/mod.rs
terrybrashaw/ni_ce
cf3c2c71a78a567eab8e387d716a15b913bd92c2
use failure::{Error, ResultExt}; use hex; use hmac::{Hmac, Mac}; use http; use rust_decimal::Decimal as d128; use serde::de::DeserializeOwned; use serde::de::{Deserialize, Deserializer, Visitor}; use serde; use serde_json; use sha2::Sha512; use std::collections::HashMap; use std::fmt::{self, Display, Formatter}; use std::str::FromStr; use {HttpClient, Query}; pub const API_HOST: &str = "https://api.exmo.com"; #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)] pub struct Credential { pub key: String, pub secret: String, pub nonce: i64, } #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)] pub struct Currency(String); impl FromStr for Currency { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(Currency(s.to_uppercase())) } } impl Display for Currency { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { let &Currency(ref currency) = self; f.write_str(currency) } } #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Serialize)] pub struct CurrencyPair(pub Currency, pub Currency); impl CurrencyPair { pub fn base(&self) -> &Currency { let &CurrencyPair(ref base, _) = self; base } pub fn quote(&self) -> &Currency { let &CurrencyPair(_, ref quote) = self; quote } } impl Display for CurrencyPair { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { write!(f, "{}_{}", self.base(), self.quote()) } } impl<'de> Deserialize<'de> for CurrencyPair { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> { struct CurrencyPairVisitor; impl<'de> Visitor<'de> for CurrencyPairVisitor { type Value = CurrencyPair; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("a string containing two currencies separated by an underscore") } fn visit_str<E>(self, pair: &str) -> Result<Self::Value, E> where E: serde::de::Error { let currencies: Vec<&str> = pair.split('_').collect(); if currencies.len() < 2 { return Err(E::invalid_value(serde::de::Unexpected::Str(pair), &self)); } let base = Currency::from_str(currencies[0]).map_err(serde::de::Error::custom)?; let quote = Currency::from_str(currencies[1]).map_err(serde::de::Error::custom)?; Ok(CurrencyPair(base, quote)) } } deserializer.deserialize_str(CurrencyPairVisitor) } } #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)] #[serde(rename_all = "lowercase")] pub enum Side { Buy, Sell, } #[derive(Debug, PartialEq, Eq, Copy, Hash, PartialOrd, Ord, Clone, Deserialize, Serialize)] pub enum OrderInstruction { LimitBuy, LimitSell, MarketBuy, MarketSell, MarketBuyTotal, MarketSellTotal, } impl Display for OrderInstruction { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { match *self { OrderInstruction::LimitBuy => f.write_str("buy"), OrderInstruction::LimitSell => f.write_str("sell"), OrderInstruction::MarketBuy => f.write_str("market_buy"), OrderInstruction::MarketSell => f.write_str("market_sell"), OrderInstruction::MarketBuyTotal => f.write_str("market_buy_total"), OrderInstruction::MarketSellTotal => f.write_str("market_sell_total"), } } } #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)] pub struct Orderbook { pub ask_quantity: d128, pub ask_amount: d128, pub ask_top: d128, pub bid_quantity: d128, pub bid_amount: d128, pub bid_top: d128, pub ask: Vec<(d128, d128, d128)>, pub bid: Vec<(d128, d128, d128)>, } #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] pub struct UserInfo { pub uid: i64, pub server_date: u64, pub balances: HashMap<Currency, d128>, pub reserved: HashMap<Currency, d128>, } #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)] pub struct Order { pub order_id: i64, } pub fn get_user_info<Client>( client: &mut Client, host: &str, credential: &Credential, ) -> Result<UserInfo, Error> where Client: HttpClient, { let query = { let mut query = Query::with_capacity(2); query.append_param("nonce", credential.nonce.to_string()); query.to_string() }; let mut http_request = http::request::Builder::new() .method(http::Method::POST) .uri(format!("{}/v1/user_info?{}", host, query)) .body(query)?; sign_private_request(&mut http_request, credential)?; let http_response = client.send(&http_request)?; deserialize_private_response(&http_response) } pub fn place_limit_order<Client>( client: &mut Client, host: &str, credential: &Credential, product: &CurrencyPair, price: d128, quantity: d128, side: Side, ) -> Result<(), Error> where Client: HttpClient, { let query = { let mut query = Query::with_capacity(5); query.append_param("nonce", credential.nonce.to_string()); query.append_param("pair", product.to_string()); query.append_param("quantity", quantity.to_string()); query.append_param("price", price.to_string()); match side { Side::Buy => query.append_param("type", "buy"), Side::Sell => query.append_param("type", "sell"), } query.to_string() }; let mut http_request = http::request::Builder::new() .method(http::Method::POST) .uri(format!("{}/v1/order_create?{}", host, query)) .body(query)?; sign_private_request(&mut http_request, credential)?; client.send(&http_request)?; Ok(()) } pub fn get_orderbooks<Client>( client: &mut Client, host: &str, products: &[&CurrencyPair], ) -> Result<HashMap<CurrencyPair, Orderbook>, Error> where Client: HttpClient, { let products: Vec<String> = products.iter().map(ToString::to_string).collect(); let query = { let mut query = Query::with_capacity(2); query.append_param("pair", products.as_slice().join(",")); query.append_param("limit", "100"); query.to_string() }; let http_request = http::request::Builder::new() .method(http::Method::GET) .uri(format!("{}/v1/order_book?{}", host, query)) .body(String::new())?; let http_response = client.send(&http_request)?; deserialize_public_response(&http_response) } #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)] struct ErrorResponse { pub result: bool, pub error: String, } fn sign_private_request( request: &mut http::Request<String>, credential: &Credential, ) -> Result<(), Error> { let mut mac = Hmac::<Sha512>::new(credential.secret.as_bytes()).map_err(|e| format_err!("{:?}", e))?; mac.input(request.body().as_bytes()); let signature = hex::encode(mac.result().code().to_vec()); let headers = request.headers_mut(); headers.insert("Key", credential.key.clone().parse().unwrap()); headers.insert("Sign", signature.parse().unwrap()); Ok(()) } fn deserialize_private_response<T>(response: &http::Response<String>) -> Result<T, Error> where T: DeserializeOwned { let body = response.body(); let response: serde_json::Value = serde_json::from_str(body)?; let is_error = response .as_object() .map(|object| { match object.get("result") { Some(&serde_json::Value::Bool(result)) => !result, _ => false, } }) .unwrap_or(false); if is_error { let error: ErrorResponse = serde_json::from_value(response) .with_context(|_| format!("failed to deserialize: \"{}\"", body))?; Err(format_err!("Server returned: {}", error.error)) } else { let response = serde_json::from_value(response) .context(format!("failed to deserialize: \"{}\"", body))?; Ok(response) } } fn deserialize_public_response<T>(response: &http::Response<String>) -> Result<T, Error> where T: DeserializeOwned { let body = response.body(); Ok(serde_json::from_str(body)?) }
use failure::{Error, ResultExt}; use hex; use hmac::{Hmac, Mac}; use http; use rust_decimal::Decimal as d128; use serde::de::DeserializeOwned; use serde::de::{Deserialize, Deserializer, Visitor}; use serde; use serde_json; use sha2::Sha512; use std::collections::HashMap; use std::fmt::{self, Display, Formatter}; use std::str::FromStr; use {HttpClient, Query}; pub const API_HOST: &str = "https://api.exmo.com"; #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)] pub struct Credential { pub key: String, pub secret: String, pub nonce: i64, } #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)] pub struct Currency(String); impl FromStr for Currency { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(Currency(s.to_uppercase())) } } impl Display for Currency { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { let &Currency(ref currency) = self; f.write_str(currency) } } #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Serialize)] pub struct CurrencyPair(pub Currency, pub Currency); impl CurrencyPair { pub fn base(&self) -> &Currency { let &CurrencyPair(ref base, _) = self; base } pub fn quote(&self) -> &Currency { let &CurrencyPair(_, ref quote) = self; quote } } impl Display for CurrencyPair { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { write!(f, "{}_{}", self.base(), self.quote()) } } impl<'de> Deserialize<'de> for CurrencyPair { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> { struct CurrencyPairVisitor; impl<'de> Visitor<'de> for CurrencyPairVisitor { type Value = CurrencyPair; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("a string containing two currencies separated by an underscore") } fn visit_str<E>(self, pair: &str) -> Result<Self::Value, E> where E: serde::de::Error { let currencies: Vec<&str> = pair.split('_').collect(); if currencies.len() < 2 { return Err(E::invalid_value(serde::de::Unexpected::Str(pair), &self)); } let base = Currency::from_str(currencies[0]).map_err(serde::de::Error::custom)?; let quote = Currency::from_str(currencies[1]).map_err(serde::de::Error::custom)?; Ok(CurrencyPair(base, quote)) } } deserializer.deserialize_str(CurrencyPairVisitor) } } #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)] #[serde(rename_all = "lowercase")] pub enum Side { Buy, Sell, } #[derive(Debug, PartialEq, Eq, Copy, Hash, PartialOrd, Ord, Clone, Deserialize, Serialize)] pub enum OrderInstruction { LimitBuy, LimitSell, MarketBuy, MarketSell, MarketBuyTotal, MarketSellTotal, } impl Display for OrderInstruction { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { match *self { OrderInstruction::LimitBuy => f.write_str("buy"), OrderInstruction::LimitSell => f.write_str("sell"), OrderInstruction::MarketBuy => f.write_str("market_buy"), OrderInstruction::MarketSell => f.write_str("market_sell"), OrderInstruction::MarketBuyTotal => f.write_str("market_buy_total"), OrderInstruction::MarketSellTotal => f.write_str("market_sell_total"), } } } #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)] pub struct Orderbook { pub ask_quantity: d128, pub ask_amount: d128, pub ask_top: d128, pub bid_quantity: d128, pub bid_amount: d128, pub bid_top: d128, pub ask: Vec<(d128, d128, d128)>, pub bid: Vec<(d128, d128, d128)>, } #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] pub struct UserInfo { pub uid: i64, pub server_date: u64, pub balances: HashMap<Currency, d128>, pub reserved: HashMap<Currency, d128>, } #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)] pub struct Order { pub order_id: i64, }
pub fn place_limit_order<Client>( client: &mut Client, host: &str, credential: &Credential, product: &CurrencyPair, price: d128, quantity: d128, side: Side, ) -> Result<(), Error> where Client: HttpClient, { let query = { let mut query = Query::with_capacity(5); query.append_param("nonce", credential.nonce.to_string()); query.append_param("pair", product.to_string()); query.append_param("quantity", quantity.to_string()); query.append_param("price", price.to_string()); match side { Side::Buy => query.append_param("type", "buy"), Side::Sell => query.append_param("type", "sell"), } query.to_string() }; let mut http_request = http::request::Builder::new() .method(http::Method::POST) .uri(format!("{}/v1/order_create?{}", host, query)) .body(query)?; sign_private_request(&mut http_request, credential)?; client.send(&http_request)?; Ok(()) } pub fn get_orderbooks<Client>( client: &mut Client, host: &str, products: &[&CurrencyPair], ) -> Result<HashMap<CurrencyPair, Orderbook>, Error> where Client: HttpClient, { let products: Vec<String> = products.iter().map(ToString::to_string).collect(); let query = { let mut query = Query::with_capacity(2); query.append_param("pair", products.as_slice().join(",")); query.append_param("limit", "100"); query.to_string() }; let http_request = http::request::Builder::new() .method(http::Method::GET) .uri(format!("{}/v1/order_book?{}", host, query)) .body(String::new())?; let http_response = client.send(&http_request)?; deserialize_public_response(&http_response) } #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)] struct ErrorResponse { pub result: bool, pub error: String, } fn sign_private_request( request: &mut http::Request<String>, credential: &Credential, ) -> Result<(), Error> { let mut mac = Hmac::<Sha512>::new(credential.secret.as_bytes()).map_err(|e| format_err!("{:?}", e))?; mac.input(request.body().as_bytes()); let signature = hex::encode(mac.result().code().to_vec()); let headers = request.headers_mut(); headers.insert("Key", credential.key.clone().parse().unwrap()); headers.insert("Sign", signature.parse().unwrap()); Ok(()) } fn deserialize_private_response<T>(response: &http::Response<String>) -> Result<T, Error> where T: DeserializeOwned { let body = response.body(); let response: serde_json::Value = serde_json::from_str(body)?; let is_error = response .as_object() .map(|object| { match object.get("result") { Some(&serde_json::Value::Bool(result)) => !result, _ => false, } }) .unwrap_or(false); if is_error { let error: ErrorResponse = serde_json::from_value(response) .with_context(|_| format!("failed to deserialize: \"{}\"", body))?; Err(format_err!("Server returned: {}", error.error)) } else { let response = serde_json::from_value(response) .context(format!("failed to deserialize: \"{}\"", body))?; Ok(response) } } fn deserialize_public_response<T>(response: &http::Response<String>) -> Result<T, Error> where T: DeserializeOwned { let body = response.body(); Ok(serde_json::from_str(body)?) }
pub fn get_user_info<Client>( client: &mut Client, host: &str, credential: &Credential, ) -> Result<UserInfo, Error> where Client: HttpClient, { let query = { let mut query = Query::with_capacity(2); query.append_param("nonce", credential.nonce.to_string()); query.to_string() }; let mut http_request = http::request::Builder::new() .method(http::Method::POST) .uri(format!("{}/v1/user_info?{}", host, query)) .body(query)?; sign_private_request(&mut http_request, credential)?; let http_response = client.send(&http_request)?; deserialize_private_response(&http_response) }
function_block-full_function
[ { "content": "fn private_signature(credential: &Credential, query: &str) -> Result<String, Error> {\n\n let mut mac =\n\n Hmac::<Sha256>::new(credential.secret.as_bytes()).map_err(|e| format_err!(\"{:?}\", e))?;\n\n mac.input(query.as_bytes());\n\n Ok(hex::encode(mac.result().code().to_vec()))\n...
Rust
src/utils.rs
ripe-tech/pconvert-rust
cf9ffcfc59d5838cf4d74a2c6c666e3f94f7cdc3
use crate::blending::demultiply_image; use crate::errors::PConvertError; use image::codecs::png::{CompressionType, FilterType, PngDecoder, PngEncoder}; use image::ImageDecoder; use image::{ColorType, ImageBuffer, Rgba}; use std::fs::File; use std::io::{BufWriter, Read, Write}; pub fn decode_png( readable_stream: impl Read, demultiply: bool, ) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>, PConvertError> { let decoder = PngDecoder::new(readable_stream)?; let (width, height) = decoder.dimensions(); let mut reader = decoder.into_reader()?; let mut bytes = Vec::<u8>::new(); reader.read_to_end(&mut bytes)?; let mut img = ImageBuffer::from_vec(width, height, bytes).unwrap(); if demultiply { demultiply_image(&mut img) } Ok(img) } pub fn read_png_from_file( file_in: String, demultiply: bool, ) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>, PConvertError> { let file = File::open(file_in)?; decode_png(file, demultiply) } pub fn encode_png( writable_buff: impl Write, png: &ImageBuffer<Rgba<u8>, Vec<u8>>, compression: CompressionType, filter: FilterType, ) -> Result<(), PConvertError> { let buff = BufWriter::new(writable_buff); let encoder = PngEncoder::new_with_quality(buff, compression, filter); Ok(encoder.encode(&png, png.width(), png.height(), ColorType::Rgba8)?) } pub fn write_png_to_file( file_out: String, png: &ImageBuffer<Rgba<u8>, Vec<u8>>, compression: CompressionType, filter: FilterType, ) -> Result<(), PConvertError> { let file = File::create(&file_out)?; encode_png(file, png, compression, filter) } pub fn write_png_to_file_d( file_out: String, png: &ImageBuffer<Rgba<u8>, Vec<u8>>, ) -> Result<(), PConvertError> { let file = File::create(&file_out)?; encode_png(file, png, CompressionType::Fast, FilterType::NoFilter) } #[cfg(not(feature = "wasm-extension"))] pub fn write_png_parallel( file_out: String, png: &ImageBuffer<Rgba<u8>, Vec<u8>>, compression: CompressionType, filter: FilterType, ) -> Result<(), PConvertError> { let writer = File::create(file_out)?; let mut header = mtpng::Header::new(); header.set_size(png.width(), png.height())?; header.set_color(mtpng::ColorType::TruecolorAlpha, 8)?; let mut options = mtpng::encoder::Options::new(); options.set_compression_level(mtpng_compression_from(compression))?; options.set_filter_mode(mtpng::Mode::Fixed(mtpng_filter_from(filter)))?; let mut encoder = mtpng::encoder::Encoder::new(writer, &options); encoder.write_header(&header)?; encoder.write_image_rows(&png)?; encoder.finish()?; Ok(()) } #[cfg(feature = "wasm-extension")] pub fn write_png_parallel( file_out: String, png: &ImageBuffer<Rgba<u8>, Vec<u8>>, compression: CompressionType, filter: FilterType, ) -> Result<(), PConvertError> { write_png_to_file(file_out, png, compression, filter) } pub fn image_compression_from(compression: String) -> CompressionType { match compression.trim().to_lowercase().as_str() { "best" => CompressionType::Best, "default" => CompressionType::Default, "fast" => CompressionType::Fast, "huffman" => CompressionType::Huffman, "rle" => CompressionType::Rle, _ => CompressionType::Fast, } } pub fn image_filter_from(filter: String) -> FilterType { match filter.trim().to_lowercase().as_str() { "avg" => FilterType::Avg, "nofilter" => FilterType::NoFilter, "paeth" => FilterType::Paeth, "sub" => FilterType::Sub, "up" => FilterType::Up, _ => FilterType::NoFilter, } } #[cfg(not(feature = "wasm-extension"))] fn mtpng_compression_from(compression: CompressionType) -> mtpng::CompressionLevel { match compression { CompressionType::Default => mtpng::CompressionLevel::Default, CompressionType::Best => mtpng::CompressionLevel::High, CompressionType::Fast => mtpng::CompressionLevel::Fast, _ => mtpng::CompressionLevel::Fast, } } #[cfg(not(feature = "wasm-extension"))] fn mtpng_filter_from(filter: FilterType) -> mtpng::Filter { match filter { FilterType::Avg => mtpng::Filter::Average, FilterType::Paeth => mtpng::Filter::Paeth, FilterType::Sub => mtpng::Filter::Sub, FilterType::Up => mtpng::Filter::Up, FilterType::NoFilter => mtpng::Filter::None, _ => mtpng::Filter::None, } } pub fn max<T: PartialOrd>(x: T, y: T) -> T { if x > y { x } else { y } } pub fn min<T: PartialOrd>(x: T, y: T) -> T { if x < y { x } else { y } }
use crate::blending::demultiply_image; use crate::errors::PConvertError; use image::codecs::png::{CompressionType, FilterType, PngDecoder, PngEncoder}; use image::ImageDecoder; use image::{ColorType, ImageBuffer, Rgba}; use std::fs::File; use std::io::{BufWriter, Read, Write}; pub fn decode_png( readable_stream: impl Read, demultiply: bool, ) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>, PConvertError> { let decoder = PngDecoder::new(readable_stream)?; let (width, height) = decoder.dimensions(); let mut reader = decoder.into_reader()?; let mut bytes = Vec::<u8>::new(); reader.read_to_end(&mut bytes)?; let mut img = ImageBuffer::from_vec(width, height, bytes).unwrap(); if demultiply { demultiply_image(&mut img) } Ok(img) } pub fn read_png_from_file( file_in: String, demultiply: bool, ) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>, PConvertError> { let file = File::open(file_in)?; decode_png(file, demultiply) } pub fn encode_png( writable_buff: impl Write, png: &ImageBuffer<Rgba<u8>, Vec<u8>>, compression: CompressionType, filter: FilterType, ) -> Result<(), PConvertError> { let buff = BufWriter::new(writable_buff); let encoder = PngEncoder::new_with_quality(buff, compression, filter); Ok(encoder.encode(&png, png.width(), png.height(), ColorType::Rgba8)?) } pub fn write_png_to_file( file_out: String, png: &ImageBuffer<Rgba<u8>, Vec<u8>>, compression: CompressionType, filter: FilterType, ) -> Result<(), PConvertError> { let file = File::create(&file_out)?; encode_png(file, png, compression, filter) } pub fn write_png_to_file_d( file_out: String, png: &ImageBuffer<Rgba<u8>, Vec<u8>>, ) -> Result<(), PConvertError> { let file = File::create(&file_out)?; encode_png(file, png, CompressionType::Fast, FilterType::NoFilter) } #[cfg(not(feature = "wasm-extension"))] pub fn write_png_parallel( file_out: String, png: &ImageBuffer<Rgba<u8>, Vec<u8>>, compression: CompressionType, filter: FilterType, ) -> Result<(), PConvertError> { let writer = File::create(file_out)?; let mut header = mtpng::Header::new(); header.set_size(png.width(), png.height())?; header.set_color(mtpng::ColorType::TruecolorAlpha, 8)?; let mut options = mtpng::encoder::Options::new(); options.set_compression_level(mtpng_compression_from(compression))?; options.set_filter_mode(mtpng::Mode::Fixed(mtpng_filter_from(filter)))?; let mut encoder = mtpng::encoder::Encoder::new(writer, &options); encoder.write_header(&header)?; encoder.write_image_rows(&png)?; encoder.finish()?; Ok(()) } #[cfg(feature = "wasm-extension")]
pub fn image_compression_from(compression: String) -> CompressionType { match compression.trim().to_lowercase().as_str() { "best" => CompressionType::Best, "default" => CompressionType::Default, "fast" => CompressionType::Fast, "huffman" => CompressionType::Huffman, "rle" => CompressionType::Rle, _ => CompressionType::Fast, } } pub fn image_filter_from(filter: String) -> FilterType { match filter.trim().to_lowercase().as_str() { "avg" => FilterType::Avg, "nofilter" => FilterType::NoFilter, "paeth" => FilterType::Paeth, "sub" => FilterType::Sub, "up" => FilterType::Up, _ => FilterType::NoFilter, } } #[cfg(not(feature = "wasm-extension"))] fn mtpng_compression_from(compression: CompressionType) -> mtpng::CompressionLevel { match compression { CompressionType::Default => mtpng::CompressionLevel::Default, CompressionType::Best => mtpng::CompressionLevel::High, CompressionType::Fast => mtpng::CompressionLevel::Fast, _ => mtpng::CompressionLevel::Fast, } } #[cfg(not(feature = "wasm-extension"))] fn mtpng_filter_from(filter: FilterType) -> mtpng::Filter { match filter { FilterType::Avg => mtpng::Filter::Average, FilterType::Paeth => mtpng::Filter::Paeth, FilterType::Sub => mtpng::Filter::Sub, FilterType::Up => mtpng::Filter::Up, FilterType::NoFilter => mtpng::Filter::None, _ => mtpng::Filter::None, } } pub fn max<T: PartialOrd>(x: T, y: T) -> T { if x > y { x } else { y } } pub fn min<T: PartialOrd>(x: T, y: T) -> T { if x < y { x } else { y } }
pub fn write_png_parallel( file_out: String, png: &ImageBuffer<Rgba<u8>, Vec<u8>>, compression: CompressionType, filter: FilterType, ) -> Result<(), PConvertError> { write_png_to_file(file_out, png, compression, filter) }
function_block-full_function
[ { "content": "/// Demultiplies an image buffer, by applying the demultiply operation over the\n\n/// complete set of pixels in the provided image buffer.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `img` - The image buffer to demultiply.\n\npub fn demultiply_image(img: &mut ImageBuffer<Rgba<u8>, Vec<u8>>) {\n\n ...