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
tools/sdk-sync/src/fs.rs
eduardomourar/smithy-rs
817bf68e69da1d1ef14f8e79a27ec39a6d92bbad
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ use anyhow::{Context, Result}; use gitignore::Pattern; use smithy_rs_tool_common::macros::here; use smithy_rs_tool_common::shell::handle_failure; use std::error::Error; use std::fmt::Display; use std::path::{Path, PathBuf}; use std::process::Command; use tracing::{info, warn}; static HANDWRITTEN_DOTFILE: &str = ".handwritten"; #[cfg_attr(test, mockall::automock)] pub trait Fs: Send + Sync { fn delete_all_generated_files_and_folders(&self, directory: &Path) -> Result<()>; fn find_handwritten_files_and_folders( &self, aws_sdk_path: &Path, build_artifacts_path: &Path, ) -> Result<Vec<PathBuf>>; fn remove_dir_all_idempotent(&self, path: &Path) -> Result<()>; fn read_to_string(&self, path: &Path) -> Result<String>; fn remove_file_idempotent(&self, path: &Path) -> Result<()>; fn recursive_copy(&self, source: &Path, destination: &Path) -> Result<()>; fn copy(&self, source: &Path, destination: &Path) -> Result<()>; } #[derive(Debug, Default)] pub struct DefaultFs; impl DefaultFs { pub fn new() -> Self { Self } } impl Fs for DefaultFs { fn delete_all_generated_files_and_folders(&self, directory: &Path) -> Result<()> { let dotfile_path = directory.join(HANDWRITTEN_DOTFILE); let handwritten_files = HandwrittenFiles::from_dotfile(&dotfile_path, directory) .context(here!("loading .handwritten"))?; let generated_files = handwritten_files .generated_files_and_folders_iter() .context(here!())?; let mut file_count = 0; let mut folder_count = 0; for path in generated_files { if path.is_file() { std::fs::remove_file(path).context(here!())?; file_count += 1; } else if path.is_dir() { std::fs::remove_dir_all(path).context(here!())?; folder_count += 1; }; } info!( "Deleted {} generated files and {} entire generated directories", file_count, folder_count ); Ok(()) } fn find_handwritten_files_and_folders( &self, aws_sdk_path: &Path, build_artifacts_path: &Path, ) -> Result<Vec<PathBuf>> { let dotfile_path = aws_sdk_path.join(HANDWRITTEN_DOTFILE); let handwritten_files = HandwrittenFiles::from_dotfile(&dotfile_path, build_artifacts_path) .context(here!("loading .handwritten"))?; let files: Vec<_> = handwritten_files .handwritten_files_and_folders_iter() .context(here!())? .collect(); info!( "Found {} handwritten files and folders in aws-sdk-rust", files.len() ); Ok(files) } fn remove_dir_all_idempotent(&self, path: &Path) -> Result<()> { assert!(path.is_absolute(), "remove_dir_all_idempotent should be used with absolute paths to avoid trivial pathing issues"); match std::fs::remove_dir_all(path) { Ok(_) => Ok(()), Err(err) => match err.kind() { std::io::ErrorKind::NotFound => Ok(()), _ => Err(err).context(here!()), }, } } fn read_to_string(&self, path: &Path) -> Result<String> { Ok(std::fs::read_to_string(path)?) } fn remove_file_idempotent(&self, path: &Path) -> Result<()> { match std::fs::remove_file(path) { Ok(_) => Ok(()), Err(err) => match err.kind() { std::io::ErrorKind::NotFound => Ok(()), _ => Err(err).context(here!()), }, } } fn recursive_copy(&self, source: &Path, destination: &Path) -> Result<()> { assert!( source.is_absolute() && destination.is_absolute(), "recursive_copy should be used with absolute paths to avoid trivial pathing issues" ); let mut command = Command::new("cp"); command.arg("-r"); command.arg(source); command.arg(destination); let output = command.output()?; handle_failure("recursive_copy", &output)?; Ok(()) } fn copy(&self, source: &Path, destination: &Path) -> Result<()> { std::fs::copy(source, destination)?; Ok(()) } } #[derive(Debug)] pub struct HandwrittenFiles { patterns: String, root: PathBuf, } #[derive(Debug, PartialEq, Eq)] pub enum FileKind { Generated, Handwritten, } impl HandwrittenFiles { pub fn from_dotfile(dotfile_path: &Path, root: &Path) -> Result<Self, HandwrittenFilesError> { let handwritten_files = Self { patterns: std::fs::read_to_string(dotfile_path)?, root: root.canonicalize()?, }; let dotfile_kind = handwritten_files.file_kind(&root.join(HANDWRITTEN_DOTFILE)); if dotfile_kind == FileKind::Generated { warn!( "Your handwritten dotfile at {} isn't marked as handwritten, is this intentional?", dotfile_path.display() ); } Ok(handwritten_files) } fn patterns(&self) -> impl Iterator<Item = Pattern> { self.patterns .lines() .filter(|line| !line.is_empty()) .flat_map(move |line| Pattern::new(line, &self.root)) } pub fn file_kind(&self, path: &Path) -> FileKind { for pattern in self.patterns() { if pattern.is_excluded(path, path.is_dir()) { return FileKind::Handwritten; } } FileKind::Generated } pub fn generated_files_and_folders_iter( &self, ) -> Result<impl Iterator<Item = PathBuf> + '_, HandwrittenFilesError> { self.files_and_folders_iter(FileKind::Generated) } pub fn handwritten_files_and_folders_iter( &self, ) -> Result<impl Iterator<Item = PathBuf> + '_, HandwrittenFilesError> { self.files_and_folders_iter(FileKind::Handwritten) } fn files_and_folders_iter( &self, kind: FileKind, ) -> Result<impl Iterator<Item = PathBuf> + '_, HandwrittenFilesError> { let files = std::fs::read_dir(&self.root)?.collect::<Result<Vec<_>, _>>()?; Ok(files .into_iter() .map(|entry| entry.path()) .filter(move |path| self.file_kind(path) == kind)) } } #[derive(Debug)] pub enum HandwrittenFilesError { Io(std::io::Error), GitIgnore(gitignore::Error), } impl Display for HandwrittenFilesError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Io(err) => { write!(f, "IO error: {}", err) } Self::GitIgnore(err) => { write!(f, "gitignore error: {}", err) } } } } impl std::error::Error for HandwrittenFilesError { fn source(&self) -> Option<&(dyn Error + 'static)> { match self { Self::Io(err) => Some(err), Self::GitIgnore(err) => Some(err), } } } impl From<std::io::Error> for HandwrittenFilesError { fn from(error: std::io::Error) -> Self { Self::Io(error) } } impl From<gitignore::Error> for HandwrittenFilesError { fn from(error: gitignore::Error) -> Self { Self::GitIgnore(error) } } #[cfg(test)] mod tests { use super::{DefaultFs, Fs, HANDWRITTEN_DOTFILE}; use pretty_assertions::assert_eq; use std::fs::File; use tempfile::TempDir; fn create_test_dir_and_handwritten_files_dotfile(handwritten_files: &[&str]) -> TempDir { let dir = TempDir::new().unwrap(); let file_path = dir.path().join(HANDWRITTEN_DOTFILE); let handwritten_files = handwritten_files.join("\n\n"); std::fs::write(file_path, handwritten_files).expect("failed to write"); dir } fn create_test_file(temp_dir: &TempDir, name: &str) { let file_path = temp_dir.path().join(name); let f = File::create(file_path).unwrap(); f.sync_all().unwrap(); } fn create_test_dir(temp_dir: &TempDir, name: &str) { let dir_path = temp_dir.path().join(name); std::fs::create_dir(dir_path).unwrap(); } #[test] fn test_delete_all_generated_files_and_folders_doesnt_delete_handwritten_files_and_folders() { let handwritten_files = &[HANDWRITTEN_DOTFILE, "foo.txt", "bar/"]; let dir = create_test_dir_and_handwritten_files_dotfile(handwritten_files); create_test_file(&dir, "foo.txt"); create_test_dir(&dir, "bar"); let expected_files_and_folders: Vec<_> = std::fs::read_dir(dir.path()) .unwrap() .map(|entry| entry.unwrap().path()) .collect(); DefaultFs::new() .delete_all_generated_files_and_folders(dir.path()) .unwrap(); let actual_files_and_folders: Vec<_> = std::fs::read_dir(dir.path()) .unwrap() .map(|entry| entry.unwrap().path()) .collect(); assert_eq!(expected_files_and_folders, actual_files_and_folders); } #[test] fn test_delete_all_generated_files_and_folders_deletes_generated_files_and_folders() { let handwritten_files = &[HANDWRITTEN_DOTFILE, "foo.txt", "bar/"]; let dir = create_test_dir_and_handwritten_files_dotfile(handwritten_files); create_test_file(&dir, "foo.txt"); create_test_dir(&dir, "bar"); let expected_files_and_folders: Vec<_> = std::fs::read_dir(dir.path()) .unwrap() .map(|entry| entry.unwrap().path()) .collect(); create_test_file(&dir, "bar.txt"); create_test_dir(&dir, "qux"); DefaultFs::new() .delete_all_generated_files_and_folders(dir.path()) .unwrap(); let actual_files_and_folders: Vec<_> = std::fs::read_dir(dir.path()) .unwrap() .map(|entry| entry.unwrap().path()) .collect(); assert_eq!(expected_files_and_folders, actual_files_and_folders); } #[test] fn test_delete_all_generated_files_and_folders_ignores_comment_and_empty_lines() { let handwritten_files = &[HANDWRITTEN_DOTFILE, "# a fake comment", ""]; let dir = create_test_dir_and_handwritten_files_dotfile(handwritten_files); let expected_files_and_folders: Vec<_> = std::fs::read_dir(dir.path()) .unwrap() .map(|entry| entry.unwrap().path()) .collect(); DefaultFs::new() .delete_all_generated_files_and_folders(dir.path()) .unwrap(); let actual_files_and_folders: Vec<_> = std::fs::read_dir(dir.path()) .unwrap() .map(|entry| entry.unwrap().path()) .collect(); assert_eq!(expected_files_and_folders, actual_files_and_folders); assert_eq!(actual_files_and_folders.len(), 1) } #[test] fn test_find_handwritten_files_works() { let handwritten_files = &[HANDWRITTEN_DOTFILE, "foo.txt", "bar/"]; let sdk_dir = create_test_dir_and_handwritten_files_dotfile(handwritten_files); let build_artifacts_dir = create_test_dir_and_handwritten_files_dotfile(handwritten_files); create_test_file(&build_artifacts_dir, "foo.txt"); create_test_dir(&build_artifacts_dir, "bar"); let expected_files_and_folders: Vec<_> = std::fs::read_dir(build_artifacts_dir.path()) .unwrap() .map(|entry| entry.unwrap().path().canonicalize().unwrap()) .collect(); create_test_file(&build_artifacts_dir, "bar.txt"); create_test_dir(&build_artifacts_dir, "qux"); let actual_files_and_folders = DefaultFs::new() .find_handwritten_files_and_folders(sdk_dir.path(), build_artifacts_dir.path()) .unwrap(); assert_eq!(expected_files_and_folders, actual_files_and_folders); } }
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ use anyhow::{Context, Result}; use gitignore::Pattern; use smithy_rs_tool_common::macros::here; use smithy_rs_tool_common::shell::handle_failure; use std::error::Error; use std::fmt::Display; use std::path::{Path, PathBuf}; use std::process::Command; use tracing::{info, warn}; static HANDWRITTEN_DOTFILE: &str = ".handwritten"; #[cfg_attr(test, mockall::automock)] pub trait Fs: Send + Sync { fn delete_all_generated_files_and_folders(&self, directory: &Path) -> Result<()>; fn find_handwritten_files_and_folders( &self, aws_sdk_path: &Path, build_artifacts_path: &Path, ) -> Result<Vec<PathBuf>>; fn remove_dir_all_idempotent(&self, path: &Path) -> Result<()>; fn read_to_string(&self, path: &Path) -> Result<String>; fn remove_file_idempotent(&self, path: &Path) -> Result<()>; fn recursive_copy(&self, source: &Path, destination: &Path) -> Result<()>; fn copy(&self, source: &Path, destination: &Path) -> Result<()>; } #[derive(Debug, Default)] pub struct DefaultFs; impl DefaultFs { pub fn new() -> Self { Self } } impl Fs for DefaultFs { fn delete_all_generated_files_and_folders(&self, directory: &Path) -> Result<()> { let dotfile_path = directory.join(HANDWRITTEN_DOTFILE); let handwritten_files = HandwrittenFiles::from_dotfile(&dotfile_path, directory) .context(here!("loading .handwritten"))?; let generated_files = handwritten_files .generated_files_and_folders_iter() .context(here!())?; let mut file_count = 0; let mut folder_count = 0; for path in generated_files { if path.is_file() { std::fs::remove_file(path).context(here!())?; file_count += 1; } else if path.is_dir() { std::fs::remove_dir_all(path).context(here!())?; folder_count += 1; }; } info!( "Deleted {} generated files and {} entire generated directories", file_count, folder_count ); Ok(()) } fn find_handwritten_files_and_folders( &self, aws_sdk_path: &Path, build_artifacts_path: &Path, ) -> Result<Vec<PathBuf>> { let dotfile_path = aws_sdk_path.join(HANDWRITTEN_DOTFILE); let handwritten_files = HandwrittenFiles::from_dotfile(&dotfile_path, build_artifacts_path) .context(here!("loading .handwritten"))?; let files: Vec<_> = handwritten_files .handwritten_files_and_folders_iter() .context(here!())? .collect(); info!( "Found {} handwritten files and folders in aws-sdk-rust", files.len() ); Ok(files) } fn remove_dir_all_idempotent(&self, path: &Path) -> Result<()> { assert!(path.is_absolute(), "remove_dir_all_idempotent should be used with absolute paths to avoid trivial pathing issues"); match std::fs::remove_dir_all(path) { Ok(_) => Ok(()), Err(err) => match err.kind() { std::io::ErrorKind::NotFound => Ok(()), _ => Err(err).context(here!()), }, } } fn read_to_string(&self, path: &Path) -> Result<String> { Ok(std::fs::read_to_string(path)?) } fn remove_file_idempotent(&self, path: &Path) -> Result<()> { match std::fs::remove_file(path) { Ok(_) => Ok(()), Err(err) => match err.kind() { std::io::ErrorKind::NotFound => Ok(()), _ => Err(err).context(here!()), }, } } fn recursive_copy(&self, source: &Path, destination: &Path) -> Result<()> { assert!( source.is_absolute() && destination.is_absolute(), "recursive_copy should be used with absolute paths to avoid trivial pathing issues" ); let mut command = Command::new("cp"); command.arg("-r"); command.arg(source); command.arg(destination); let output = command.output()?; handle_failure("recursive_copy", &output)?; Ok(()) } fn copy(&self, source: &Path, destination: &Path) -> Result<()> { std::fs::copy(source, destination)?; Ok(()) } } #[derive(Debug)] pub struct HandwrittenFiles { patterns: String, root: PathBuf, } #[derive(Debug, PartialEq, Eq)] pub enum FileKind { Generated, Handwritten, } impl HandwrittenFiles { pub fn from_dotfile(dotfile_path: &Path, root: &Path) -> Result<Self, HandwrittenFilesError> { let handwritten_files = Self { patterns: std::fs::read_to_string(dotfile_path)?, root: root.canonicalize()?, }; let dotfile_kind = handwritten_files.file_kind(&root.join(HANDWRITTEN_DOTFILE)); if dotfile_kind == FileKind::Generated { warn!( "Your handwritten dotfile at {} isn't marked as handwritten, is this intentional?", dotfile_path.display() ); } Ok(handwritten_files) } fn patterns(&self) -> impl Iterator<Item = Pattern> { self.patterns .lines() .filter(|line| !line.is_empty()) .flat_map(move |line| Pattern::new(line, &self.root)) } pub fn file_kind(&self, path: &Path) -> FileKind { for pattern in self.patterns() { if patte
pub fn generated_files_and_folders_iter( &self, ) -> Result<impl Iterator<Item = PathBuf> + '_, HandwrittenFilesError> { self.files_and_folders_iter(FileKind::Generated) } pub fn handwritten_files_and_folders_iter( &self, ) -> Result<impl Iterator<Item = PathBuf> + '_, HandwrittenFilesError> { self.files_and_folders_iter(FileKind::Handwritten) } fn files_and_folders_iter( &self, kind: FileKind, ) -> Result<impl Iterator<Item = PathBuf> + '_, HandwrittenFilesError> { let files = std::fs::read_dir(&self.root)?.collect::<Result<Vec<_>, _>>()?; Ok(files .into_iter() .map(|entry| entry.path()) .filter(move |path| self.file_kind(path) == kind)) } } #[derive(Debug)] pub enum HandwrittenFilesError { Io(std::io::Error), GitIgnore(gitignore::Error), } impl Display for HandwrittenFilesError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Io(err) => { write!(f, "IO error: {}", err) } Self::GitIgnore(err) => { write!(f, "gitignore error: {}", err) } } } } impl std::error::Error for HandwrittenFilesError { fn source(&self) -> Option<&(dyn Error + 'static)> { match self { Self::Io(err) => Some(err), Self::GitIgnore(err) => Some(err), } } } impl From<std::io::Error> for HandwrittenFilesError { fn from(error: std::io::Error) -> Self { Self::Io(error) } } impl From<gitignore::Error> for HandwrittenFilesError { fn from(error: gitignore::Error) -> Self { Self::GitIgnore(error) } } #[cfg(test)] mod tests { use super::{DefaultFs, Fs, HANDWRITTEN_DOTFILE}; use pretty_assertions::assert_eq; use std::fs::File; use tempfile::TempDir; fn create_test_dir_and_handwritten_files_dotfile(handwritten_files: &[&str]) -> TempDir { let dir = TempDir::new().unwrap(); let file_path = dir.path().join(HANDWRITTEN_DOTFILE); let handwritten_files = handwritten_files.join("\n\n"); std::fs::write(file_path, handwritten_files).expect("failed to write"); dir } fn create_test_file(temp_dir: &TempDir, name: &str) { let file_path = temp_dir.path().join(name); let f = File::create(file_path).unwrap(); f.sync_all().unwrap(); } fn create_test_dir(temp_dir: &TempDir, name: &str) { let dir_path = temp_dir.path().join(name); std::fs::create_dir(dir_path).unwrap(); } #[test] fn test_delete_all_generated_files_and_folders_doesnt_delete_handwritten_files_and_folders() { let handwritten_files = &[HANDWRITTEN_DOTFILE, "foo.txt", "bar/"]; let dir = create_test_dir_and_handwritten_files_dotfile(handwritten_files); create_test_file(&dir, "foo.txt"); create_test_dir(&dir, "bar"); let expected_files_and_folders: Vec<_> = std::fs::read_dir(dir.path()) .unwrap() .map(|entry| entry.unwrap().path()) .collect(); DefaultFs::new() .delete_all_generated_files_and_folders(dir.path()) .unwrap(); let actual_files_and_folders: Vec<_> = std::fs::read_dir(dir.path()) .unwrap() .map(|entry| entry.unwrap().path()) .collect(); assert_eq!(expected_files_and_folders, actual_files_and_folders); } #[test] fn test_delete_all_generated_files_and_folders_deletes_generated_files_and_folders() { let handwritten_files = &[HANDWRITTEN_DOTFILE, "foo.txt", "bar/"]; let dir = create_test_dir_and_handwritten_files_dotfile(handwritten_files); create_test_file(&dir, "foo.txt"); create_test_dir(&dir, "bar"); let expected_files_and_folders: Vec<_> = std::fs::read_dir(dir.path()) .unwrap() .map(|entry| entry.unwrap().path()) .collect(); create_test_file(&dir, "bar.txt"); create_test_dir(&dir, "qux"); DefaultFs::new() .delete_all_generated_files_and_folders(dir.path()) .unwrap(); let actual_files_and_folders: Vec<_> = std::fs::read_dir(dir.path()) .unwrap() .map(|entry| entry.unwrap().path()) .collect(); assert_eq!(expected_files_and_folders, actual_files_and_folders); } #[test] fn test_delete_all_generated_files_and_folders_ignores_comment_and_empty_lines() { let handwritten_files = &[HANDWRITTEN_DOTFILE, "# a fake comment", ""]; let dir = create_test_dir_and_handwritten_files_dotfile(handwritten_files); let expected_files_and_folders: Vec<_> = std::fs::read_dir(dir.path()) .unwrap() .map(|entry| entry.unwrap().path()) .collect(); DefaultFs::new() .delete_all_generated_files_and_folders(dir.path()) .unwrap(); let actual_files_and_folders: Vec<_> = std::fs::read_dir(dir.path()) .unwrap() .map(|entry| entry.unwrap().path()) .collect(); assert_eq!(expected_files_and_folders, actual_files_and_folders); assert_eq!(actual_files_and_folders.len(), 1) } #[test] fn test_find_handwritten_files_works() { let handwritten_files = &[HANDWRITTEN_DOTFILE, "foo.txt", "bar/"]; let sdk_dir = create_test_dir_and_handwritten_files_dotfile(handwritten_files); let build_artifacts_dir = create_test_dir_and_handwritten_files_dotfile(handwritten_files); create_test_file(&build_artifacts_dir, "foo.txt"); create_test_dir(&build_artifacts_dir, "bar"); let expected_files_and_folders: Vec<_> = std::fs::read_dir(build_artifacts_dir.path()) .unwrap() .map(|entry| entry.unwrap().path().canonicalize().unwrap()) .collect(); create_test_file(&build_artifacts_dir, "bar.txt"); create_test_dir(&build_artifacts_dir, "qux"); let actual_files_and_folders = DefaultFs::new() .find_handwritten_files_and_folders(sdk_dir.path(), build_artifacts_dir.path()) .unwrap(); assert_eq!(expected_files_and_folders, actual_files_and_folders); } }
rn.is_excluded(path, path.is_dir()) { return FileKind::Handwritten; } } FileKind::Generated }
function_block-function_prefixed
[ { "content": "/// Attempts to find git repository root from the given location.\n\npub fn find_git_repository_root(repo_name: &str, location: impl AsRef<Path>) -> Result<PathBuf> {\n\n let path = GetRepoRoot::new(location.as_ref()).run()?;\n\n if path.file_name() != Some(OsStr::new(repo_name)) {\n\n ...
Rust
components/merkledb/benches/transactions.rs
bishop45690/Bishop45690-BL-Exonum
fd14af39558e7e691128d24e72ed1c288e68dc0d
use criterion::{ AxisScale, Bencher, Criterion, ParameterizedBenchmark, PlotConfiguration, Throughput, }; use rand::{rngs::StdRng, Rng, RngCore, SeedableRng}; use serde_derive::{Deserialize, Serialize}; use std::{borrow::Cow, collections::HashMap, convert::TryInto}; use exonum_crypto::{Hash, PublicKey, PUBLIC_KEY_LENGTH}; use exonum_merkledb::{ impl_object_hash_for_binary_value, BinaryValue, Database, Fork, ListIndex, MapIndex, ObjectAccess, ObjectHash, ProofListIndex, ProofMapIndex, RefMut, TemporaryDB, }; const SEED: [u8; 32] = [100; 32]; const SAMPLE_SIZE: usize = 10; #[cfg(all(test, not(feature = "long_benchmarks")))] const ITEM_COUNT: [BenchParams; 10] = [ BenchParams { users: 10_000, blocks: 1, txs_in_block: 10_000, }, BenchParams { users: 100, blocks: 1, txs_in_block: 10_000, }, BenchParams { users: 10_000, blocks: 10, txs_in_block: 1_000, }, BenchParams { users: 100, blocks: 10, txs_in_block: 1_000, }, BenchParams { users: 10_000, blocks: 100, txs_in_block: 100, }, BenchParams { users: 100, blocks: 100, txs_in_block: 100, }, BenchParams { users: 10_000, blocks: 1_000, txs_in_block: 10, }, BenchParams { users: 100, blocks: 1_000, txs_in_block: 10, }, BenchParams { users: 10_000, blocks: 10_000, txs_in_block: 1, }, BenchParams { users: 100, blocks: 10_000, txs_in_block: 1, }, ]; #[cfg(all(test, feature = "long_benchmarks"))] const ITEM_COUNT: [BenchParams; 6] = [ BenchParams { users: 1_000, blocks: 10, txs_in_block: 10_000, }, BenchParams { users: 1_000, blocks: 100, txs_in_block: 1_000, }, BenchParams { users: 1_000, blocks: 1_000, txs_in_block: 100, }, BenchParams { users: 1_000, blocks: 10_000, txs_in_block: 10, }, BenchParams { users: 1_000, blocks: 100_000, txs_in_block: 1, }, BenchParams { users: 1_000, blocks: 1_000, txs_in_block: 1_000, }, ]; #[derive(Clone, Copy, Debug)] struct BenchParams { users: usize, blocks: usize, txs_in_block: usize, } #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Default)] struct Wallet { incoming: u32, outgoing: u32, history_root: Hash, } impl BinaryValue for Wallet { fn to_bytes(&self) -> Vec<u8> { bincode::serialize(self).unwrap() } fn from_bytes(bytes: Cow<[u8]>) -> Result<Self, failure::Error> { bincode::deserialize(bytes.as_ref()).map_err(From::from) } } #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] struct Transaction { sender: PublicKey, receiver: PublicKey, amount: u32, } impl BinaryValue for Transaction { fn to_bytes(&self) -> Vec<u8> { bincode::serialize(self).unwrap() } fn from_bytes(bytes: Cow<[u8]>) -> Result<Self, failure::Error> { bincode::deserialize(bytes.as_ref()).map_err(From::from) } } impl_object_hash_for_binary_value! { Transaction, Block, Wallet } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] struct Block { transactions: Vec<Transaction>, } impl BinaryValue for Block { fn to_bytes(&self) -> Vec<u8> { bincode::serialize(self).unwrap() } fn from_bytes(bytes: Cow<[u8]>) -> Result<Self, failure::Error> { bincode::deserialize(bytes.as_ref()).map_err(From::from) } } impl Transaction { fn execute(&self, fork: &Fork) { let tx_hash = self.object_hash(); let schema = RefSchema::new(fork); schema.transactions().put(&self.object_hash(), *self); let mut owner_wallet = schema.wallets().get(&self.sender).unwrap_or_default(); owner_wallet.outgoing += self.amount; owner_wallet.history_root = schema.add_transaction_to_history(&self.sender, tx_hash); schema.wallets().put(&self.sender, owner_wallet); let mut receiver_wallet = schema.wallets().get(&self.receiver).unwrap_or_default(); receiver_wallet.incoming += self.amount; receiver_wallet.history_root = schema.add_transaction_to_history(&self.receiver, tx_hash); schema.wallets().put(&self.receiver, receiver_wallet); } } struct RefSchema<T: ObjectAccess>(T); impl<T: ObjectAccess> RefSchema<T> { fn new(object_access: T) -> Self { Self(object_access) } fn transactions(&self) -> RefMut<MapIndex<T, Hash, Transaction>> { self.0.get_object("transactions") } fn blocks(&self) -> RefMut<ListIndex<T, Hash>> { self.0.get_object("blocks") } fn wallets(&self) -> RefMut<ProofMapIndex<T, PublicKey, Wallet>> { self.0.get_object("wallets") } fn wallets_history(&self, owner: &PublicKey) -> RefMut<ProofListIndex<T, Hash>> { self.0.get_object(("wallets.history", owner)) } } impl<T: ObjectAccess> RefSchema<T> { fn add_transaction_to_history(&self, owner: &PublicKey, tx_hash: Hash) -> Hash { let mut history = self.wallets_history(owner); history.push(tx_hash); history.object_hash() } } impl Block { fn execute(&self, db: &TemporaryDB) { let fork = db.fork(); for transaction in &self.transactions { transaction.execute(&fork); } RefSchema::new(&fork).blocks().push(self.object_hash()); db.merge(fork.into_patch()).unwrap(); } } fn gen_random_blocks(blocks: usize, txs_count: usize, wallets_count: usize) -> Vec<Block> { let mut rng: StdRng = SeedableRng::from_seed(SEED); let users = (0..wallets_count) .into_iter() .map(|idx| { let mut base = [0; PUBLIC_KEY_LENGTH]; rng.fill_bytes(&mut base); (idx, PublicKey::from_bytes(base.as_ref().into()).unwrap()) }) .collect::<HashMap<_, _>>(); let get_random_user = |rng: &mut StdRng| -> PublicKey { let id = rng.gen_range(0, wallets_count); *users.get(&id).unwrap() }; (0..blocks) .into_iter() .map(move |_| { let transactions = (0..txs_count) .map(|_| Transaction { sender: get_random_user(&mut rng), receiver: get_random_user(&mut rng), amount: rng.gen_range(0, 10), }) .collect(); Block { transactions } }) .collect() } pub fn bench_transactions(c: &mut Criterion) { exonum_crypto::init(); let item_counts = ITEM_COUNT.iter().cloned(); c.bench( "transactions", ParameterizedBenchmark::new( "currency_like", move |b: &mut Bencher, params: &BenchParams| { let blocks = gen_random_blocks(params.blocks, params.txs_in_block, params.users); b.iter_with_setup(TemporaryDB::new, |db| { for block in &blocks { block.execute(&db) } let snapshot = db.snapshot(); let schema = RefSchema::new(&snapshot); assert_eq!(schema.blocks().len(), params.blocks as u64); }) }, item_counts, ) .throughput(|&s| Throughput::Elements((s.txs_in_block * s.blocks).try_into().unwrap())) .plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic)) .sample_size(SAMPLE_SIZE), ); }
use criterion::{ AxisScale, Bencher, Criterion, ParameterizedBenchmark, PlotConfiguration, Throughput, }; use rand::{rngs::StdRng, Rng, RngCore, SeedableRng}; use serde_derive::{Deserialize, Serialize}; use std::{borrow::Cow, collections::HashMap, convert::TryInto}; use exonum_crypto::{Hash, PublicKey, PUBLIC_KEY_LENGTH}; use exonum_merkledb::{ impl_object_hash_for_binary_value, BinaryValue, Database, Fork, ListIndex, MapIndex, ObjectAccess, ObjectHash, ProofListIndex, ProofMapIndex, RefMut, TemporaryDB, }; const SEED: [u8; 32] = [100; 32]; const SAMPLE_SIZE: usize = 10; #[cfg(all(test, not(feature = "long_benchmarks")))] const ITEM_COUNT: [BenchParams; 10] = [ BenchParams { users: 10_000, blocks: 1, txs_in_block: 10_000, }, BenchParams { users: 100, blocks: 1, txs_in_block: 10_000, }, BenchParams { users: 10_000, blocks: 10, txs_in_block: 1_000, }, BenchParams { users: 100, blocks: 10, txs_in_block: 1_000, }, BenchParams { users: 10_000, blocks: 100, txs_in_block: 100, }, BenchParams { users: 100, blocks: 100, txs_in_block: 100, }, BenchParams { users: 10_000, blocks: 1_000, txs_in_block: 10, }, BenchParams { users: 100, blocks: 1_000, txs_in_block: 10, }, BenchParams { users: 10_000, blocks: 10_000, txs_in_block: 1, }, BenchParams { users: 100, blocks: 10_000, txs_in_block: 1, }, ]; #[cfg(all(test, feature = "long_benchmarks"))] const ITEM_COUNT: [BenchParams; 6] = [ BenchParams { users: 1_000, blocks: 10, txs_in_block: 10_000, }, BenchParams { users: 1_000, blocks: 100, txs_in_block: 1_000, }, BenchParams { users: 1_000, blocks: 1_000, txs_in_block: 100, }, BenchParams { users: 1_000, blocks: 10_000, txs_in_block: 10, }, BenchParams { users: 1_000, blocks: 100_000, txs_in_block: 1, }, BenchParams { users: 1_000, blocks: 1_000, txs_in_block: 1_000, }, ]; #[derive(Clone, Copy, Debug)] struct BenchParams { users: usize, blocks: usize, txs_in_block: usize, } #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Default)] struct Wallet { incoming: u32, outgoing: u32, history_root: Hash, } impl BinaryValue for Wallet { fn to_bytes(&self) -> Vec<u8> { bincode::serialize(self).unwrap() } fn from_bytes(bytes: Cow<[u8]>) -> Result<Self, failure::Error> { bincode::deserialize(bytes.as_ref()).map_err(From::from) } } #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] struct Transaction { sender: PublicKey, receiver: PublicKey, amount: u32, } impl BinaryValue for Transaction { fn to_bytes(&self) -> Vec<u8> { bincode::serialize(self).unwrap() } fn from_bytes(bytes: Cow<[u8]>) -> Result<Self, failure::Error> { bincode::deserialize(bytes.as_ref()).map_err(From::from) } } impl_object_hash_for_binary_value! { Transaction, Block, Wallet } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] struct Block { transactions: Vec<Transaction>, } impl BinaryValue for Block { fn to_bytes(&self) -> Vec<u8> { bincode::serialize(self).unwrap() } fn from_bytes(bytes: Cow<[u8]>) -> Result<Self, failure::Error> { bincode::deserialize(bytes.as_ref()).map_err(From::from) } } impl Transaction { fn execute(&self, fork: &Fork) { let tx_hash = self.object_hash(); let schema = RefSchema::new(fork); schema.transactions().put(&self.object_hash(), *self); let mut owner_wallet = schema.wallets().get(&self.sender).unwrap_or_default(); owner_wallet.outgoing += self.amount; owner_wallet.history_root = schema.add_transaction_to_history(&self.sender, tx_hash); schema.wallets().put(&self.sender, owner_wallet); let mut receiver_wallet = schema.wallets().get(&self.receiver).unwrap_or_default(); receiver_wallet.incoming += self.amount; receiver_wallet.history_root = schema.add_transaction_to_history(&self.receiver, tx_hash); schema.wallets().put(&self.receiver, receiver_wallet); } } struct RefSchema<T: ObjectAccess>(T); impl<T: ObjectAccess> RefSchema<T> { fn new(object_access: T) -> Self { Self(object_access) } fn transactions(&self) -> RefMut<MapIndex<T, Hash, Transaction>> { self.0.get_object("transactions") } fn blocks(&self) -> RefMut<ListIndex<T, Hash>> { self.0.get_object("blocks") } fn wallets(&self) -> RefMut<ProofMapIndex<T, PublicKey, Wallet>> { self.0.get_object("wallets") } fn wallets_history(&self, owner: &PublicKey) -> RefMut<ProofListIndex<T, Hash>> { self.0.get_object(("wallets.history", owner)) } } impl<T: ObjectAccess> RefSchema<T> { fn add_transaction_to_history(&self, owner: &PublicKey, tx_hash: Hash) -> Hash { let mut history = self.wallets_history(owner); history.push(tx_hash); history.object_hash() } } impl Block { fn execute(&self, db: &TemporaryDB) { let fork = db.fork(); for transaction in &self.transactions { transaction.execute(&fork); } RefSchema::new(&fork).blocks().push(self.object_hash()); db.merge(fork.into_patch()).unwrap(); } } fn gen_random_blocks(blocks: usize, txs_count: usize, wallets_count: usize) -> Vec<Block> { let mut rng: StdRng = SeedableRng::from_seed(SEED); let users = (0..wallets_count) .into_iter() .map(|idx| { let mut base = [0; PUBLIC_KEY_LENGTH]; rng.fill_bytes(&mut base); (idx, PublicKey::from_bytes(base.as_ref().into()).unwrap()) }) .collect::<HashMap<_, _>>(); let get_random_user = |rng: &mut StdRng| -> PublicKey { let id = rng.gen_range(0, wallets_count); *users.get(&id).unwrap() }; (0..blocks) .into_iter() .map(move |_| { let transactions = (0..txs_count) .map(|_| Transaction { sender: get_random_user(&mut rng), receiver: get_random_user(&mut rng), amount: rng.gen_range(0, 10), }) .collect(); Block { transactions } }) .collect() }
pub fn bench_transactions(c: &mut Criterion) { exonum_crypto::init(); let item_counts = ITEM_COUNT.iter().cloned(); c.bench( "transactions", ParameterizedBenchmark::new( "currency_like", move |b: &mut Bencher, params: &BenchParams| { let blocks = gen_random_blocks(params.blocks, params.txs_in_block, params.users); b.iter_with_setup(TemporaryDB::new, |db| { for block in &blocks { block.execute(&db) } let snapshot = db.snapshot(); let schema = RefSchema::new(&snapshot); assert_eq!(schema.blocks().len(), params.blocks as u64); }) }, item_counts, ) .throughput(|&s| Throughput::Elements((s.txs_in_block * s.blocks).try_into().unwrap())) .plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic)) .sample_size(SAMPLE_SIZE), ); }
function_block-full_function
[ { "content": "fn gen_keypair_from_rng(rng: &mut StdRng) -> (PublicKey, SecretKey) {\n\n use exonum::crypto::{gen_keypair_from_seed, Seed, SEED_LENGTH};\n\n\n\n let mut bytes = [0_u8; SEED_LENGTH];\n\n rng.fill(&mut bytes);\n\n gen_keypair_from_seed(&Seed::new(bytes))\n\n}\n\n\n", "file_path": "e...
Rust
src/utils.rs
Majavar/drone
7d076fe94fb701483047e96ac35b9e68100a4d66
use crate::color::Color; use ansi_term::Color::Red; use anyhow::{bail, Result}; use serde::{de, ser}; use signal_hook::{iterator::Signals, SIGINT, SIGQUIT, SIGTERM}; use std::{ env, ffi::CString, fs::OpenOptions, io::{prelude::*, ErrorKind}, os::unix::{ffi::OsStrExt, io::AsRawFd, process::CommandExt}, path::PathBuf, process::{exit, Child, Command}, sync::mpsc::{channel, RecvTimeoutError}, thread, time::Duration, }; use tempfile::TempDir; use thiserror::Error; use walkdir::WalkDir; pub fn search_rust_tool(tool: &str) -> Result<PathBuf> { let mut rustc = Command::new("rustc"); rustc.arg("--print").arg("sysroot"); let sysroot = String::from_utf8(rustc.output()?.stdout)?; for entry in WalkDir::new(sysroot.trim()) { let entry = entry?; if entry.file_name() == tool { return Ok(entry.into_path()); } } bail!("Couldn't find `{}`", tool); } pub fn run_command(mut command: Command) -> Result<()> { match command.status() { Ok(status) if status.success() => Ok(()), Ok(status) => { if let Some(code) = status.code() { bail!("`{:?}` exited with status code: {}", command, code) } else { bail!("`{:?}` terminated by signal", command,) } } Err(err) => bail!("`{:?}` failed to execute: {}", command, err), } } pub fn spawn_command(mut command: Command) -> Result<Child> { match command.spawn() { Ok(child) => Ok(child), Err(err) => bail!("`{:?}` failed to execute: {}", command, err), } } pub fn register_signals() -> Result<Signals> { Ok(Signals::new(&[SIGINT, SIGQUIT, SIGTERM])?) } #[allow(clippy::never_loop)] pub fn block_with_signals<F, R>(signals: &Signals, ignore_sigint: bool, f: F) -> Result<R> where F: Send + 'static + FnOnce() -> Result<R>, R: Send + 'static, { let (tx, rx) = channel(); thread::spawn(move || { tx.send(f()).expect("channel is broken"); }); loop { match rx.recv_timeout(Duration::from_millis(100)) { Ok(value) => return Ok(value?), Err(RecvTimeoutError::Disconnected) => bail!("channel is broken"), Err(RecvTimeoutError::Timeout) => { for signal in signals.pending() { if signal == SIGINT { if !ignore_sigint { bail!(SignalError); } } else { bail!(SignalError); } } } } } } pub fn finally<F: FnOnce()>(f: F) -> impl Drop { struct Finalizer<F: FnOnce()>(Option<F>); impl<F: FnOnce()> Drop for Finalizer<F> { fn drop(&mut self) { self.0.take().unwrap()(); } } Finalizer(Some(f)) } pub fn temp_dir() -> PathBuf { env::var_os("XDG_RUNTIME_DIR").map_or(env::temp_dir(), Into::into) } pub fn make_fifo(dir: &TempDir, name: &str) -> Result<PathBuf> { let pipe = dir.path().join(name); let c_pipe = CString::new(pipe.as_os_str().as_bytes())?; if unsafe { libc::mkfifo(c_pipe.as_ptr(), 0o644) } == -1 { return Err(std::io::Error::last_os_error().into()); } Ok(pipe) } pub fn exhaust_fifo(path: &str) -> Result<()> { let mut fifo = OpenOptions::new().read(true).open(path)?; unsafe { libc::fcntl(fifo.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK) }; let mut bytes = [0_u8; 1024]; loop { match fifo.read(&mut bytes) { Ok(_) => continue, Err(ref err) if err.kind() == ErrorKind::Interrupted => continue, Err(ref err) if err.kind() == ErrorKind::WouldBlock => break Ok(()), Err(err) => break Err(err.into()), } } } pub fn detach_pgid(command: &mut Command) { unsafe { command.pre_exec(|| { libc::setpgid(0, 0); Ok(()) }); } } pub fn check_root_result(color: Color, f: impl FnOnce() -> Result<()>) { match f() { Ok(()) => { exit(0); } Err(err) if err.is::<SignalError>() => { exit(1); } Err(err) => { eprintln!("{}: {:?}", color.bold_fg("Error", Red), err); exit(1); } } } pub fn ser_to_string<T: ser::Serialize>(value: T) -> String { serde_json::to_value(value).unwrap().as_str().unwrap().to_string() } pub fn de_from_str<T: de::DeserializeOwned>(s: &str) -> Result<T> { serde_json::from_value(serde_json::Value::String(s.to_string())).map_err(Into::into) } #[derive(Error, Debug)] #[error("signal")] struct SignalError;
use crate::color::Color; use ansi_term::Color::Red; use anyhow::{bail, Result}; use serde::{de, ser}; use signal_hook::{iterator::Signals, SIGINT, SIGQUIT, SIGTERM}; use std::{ env, ffi::CString, fs::OpenOptions, io::{prelude::*, ErrorKind}, os::unix::{ffi::OsStrExt, io::AsRawFd, process::CommandExt}, path::PathBuf, process::{exit, Child, Command}, sync::mpsc::{channel, RecvTimeoutError}, thread, time::Duration, }; use tempfile::TempDir; use thiserror::Error; use walkdir::WalkDir; pub fn search_rust_tool(tool: &str) -> Result<PathBuf> { let mut rustc = Command::new("rustc"); rustc.arg("--print").arg("sysroot"); let sysroot = String::from_utf8(rustc.output()?.stdout)?; for entry in WalkDir::new(sysroot.trim()) { let entry = entry?; if entry.file_name() == tool { return Ok(entry.into_path()); } } bail!("Couldn't find `{}`", tool); } pub fn run_command(mut command: Command) -> Result<()> { match command.status() { Ok(status) if status.success() => Ok(()), Ok(status) => { if let Some(code) = status.code() { bail!("`{:?}` exited with status code: {}", command, code) } else { bail!("`{:?}` terminated by signal", command,) } } Err(err) => bail!("`{:?}` failed to execute: {}", command, err), } } pub fn spawn_command(mut command: Command) -> Result<Child> { match command.spawn() { Ok(child) => Ok(child), Err(err) => bail!("`{:?}` failed to execute: {}", command, err), } } pub fn register_signals() -> Result<Signals> { Ok(Signals::new(&[SIGINT, SIGQUIT, SIGTERM])?) } #[allow(clippy::never_loop)] pub fn block_with_signals<F, R>(signals: &Signals, ignore_sigint: bool, f: F) -> Result<R> where F: Send + 'static + FnOnce() -> Result<R>, R: Send + 'static, { let (tx, rx) = channel(); thread::spawn(move || { tx.send(f()).expect("channel is broken"); }); loop { match rx.recv_timeout(Duration::from_millis(100)) { Ok(value) => return Ok(value?), Err(RecvTimeoutError::Disconnected) => bail!("channel is broken"), Err(RecvTimeoutError::Timeout) => { for signal in signals.pending() { if signal == SIGINT { if !ignore_sigint { bail!(SignalError); } } else { bail!(SignalError); } } } } } } pub fn finally<F: FnOnce()>(f: F) -> impl Drop { struct Finalizer<F: FnOnce()>(Option<F>); impl<F: FnOnce()> Drop for Finalizer<F> { fn drop(&mut self) { self.0.take().unwrap()(); } } Finalizer(Some(f)) } pub fn temp_dir() -> PathBuf { env::var_os("XDG_RUNTIME_DIR").map_or(env::temp_dir(), Into::into) } pub fn make_fifo(dir: &TempDir, name: &str) -> Result<PathBuf> { let pipe = dir.path().join(name); let c_pipe = CString::new(pipe.as_os_str().as_bytes())?; if unsafe { libc::mkfifo(c_pipe.as_ptr(), 0o644) } == -1 { return Err(std::io::Error::last_os_error().into()); } Ok(pipe) } pub fn exhaust_fifo(path: &str) -> Result<()> { let mut fifo = OpenOptions::new().rea
pub fn detach_pgid(command: &mut Command) { unsafe { command.pre_exec(|| { libc::setpgid(0, 0); Ok(()) }); } } pub fn check_root_result(color: Color, f: impl FnOnce() -> Result<()>) { match f() { Ok(()) => { exit(0); } Err(err) if err.is::<SignalError>() => { exit(1); } Err(err) => { eprintln!("{}: {:?}", color.bold_fg("Error", Red), err); exit(1); } } } pub fn ser_to_string<T: ser::Serialize>(value: T) -> String { serde_json::to_value(value).unwrap().as_str().unwrap().to_string() } pub fn de_from_str<T: de::DeserializeOwned>(s: &str) -> Result<T> { serde_json::from_value(serde_json::Value::String(s.to_string())).map_err(Into::into) } #[derive(Error, Debug)] #[error("signal")] struct SignalError;
d(true).open(path)?; unsafe { libc::fcntl(fifo.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK) }; let mut bytes = [0_u8; 1024]; loop { match fifo.read(&mut bytes) { Ok(_) => continue, Err(ref err) if err.kind() == ErrorKind::Interrupted => continue, Err(ref err) if err.kind() == ErrorKind::WouldBlock => break Ok(()), Err(err) => break Err(err.into()), } } }
function_block-function_prefixed
[]
Rust
src/catcollar/iouring.rs
iyzhang/demikernel
462f7e168d4ac85e758ba64a40cf051fa906e1f4
use crate::demikernel::dbuf::DataBuffer; use ::libc::socklen_t; use ::liburing::{ io_uring, io_uring_sqe, iovec, msghdr, }; use ::nix::{ errno, sys::socket::SockAddr, }; use ::runtime::fail::Fail; use ::std::{ ffi::{ c_void, CString, }, mem::MaybeUninit, os::{ raw::c_int, unix::prelude::RawFd, }, ptr::{ self, null_mut, }, }; pub struct IoUring { io_uring: io_uring, } impl IoUring { pub fn new(nentries: u32) -> Result<Self, Fail> { unsafe { let mut params: MaybeUninit<liburing::io_uring_params> = MaybeUninit::zeroed(); let mut io_uring: MaybeUninit<io_uring> = MaybeUninit::zeroed(); let ret: c_int = liburing::io_uring_queue_init_params(nentries, io_uring.as_mut_ptr(), params.as_mut_ptr()); if ret < 0 { let errno: i32 = -ret; let strerror: CString = CString::from_raw(libc::strerror(errno)); let cause: &str = strerror.to_str().unwrap_or("failed to initialize io_uring"); return Err(Fail::new(errno, cause)); } Ok(Self { io_uring: io_uring.assume_init(), }) } } pub fn push(&mut self, sockfd: RawFd, buf: DataBuffer) -> Result<u64, Fail> { let len: usize = buf.len(); let data: &[u8] = &buf[..]; let data_ptr: *const u8 = data.as_ptr(); let io_uring: &mut io_uring = &mut self.io_uring; unsafe { let sqe: *mut io_uring_sqe = liburing::io_uring_get_sqe(io_uring); if sqe.is_null() { let errno: i32 = errno::errno(); let strerror: CString = CString::from_raw(libc::strerror(errno)); let cause: &str = strerror.to_str().unwrap_or("failed to get sqe"); return Err(Fail::new(errno, cause)); } liburing::io_uring_sqe_set_data(sqe, data_ptr as *mut c_void); liburing::io_uring_prep_send(sqe, sockfd, data_ptr as *const c_void, len, 0); if liburing::io_uring_submit(io_uring) < 1 { return Err(Fail::new(libc::EAGAIN, "failed to submit push operation")); } } Ok(data_ptr as u64) } pub fn pushto(&mut self, sockfd: RawFd, addr: SockAddr, buf: DataBuffer) -> Result<u64, Fail> { let len: usize = buf.len(); let data: &[u8] = &buf[..]; let data_ptr: *const u8 = data.as_ptr(); let (sockaddr, addrlen): (&libc::sockaddr, socklen_t) = addr.as_ffi_pair(); let sockaddr_ptr: *const libc::sockaddr = sockaddr as *const libc::sockaddr; let io_uring: &mut io_uring = &mut self.io_uring; unsafe { let sqe: *mut io_uring_sqe = liburing::io_uring_get_sqe(io_uring); if sqe.is_null() { let errno: i32 = errno::errno(); let strerror: CString = CString::from_raw(libc::strerror(errno)); let cause: &str = strerror.to_str().unwrap_or("failed to get sqe"); return Err(Fail::new(errno, cause)); } liburing::io_uring_sqe_set_data(sqe, data_ptr as *mut c_void); let mut iov: iovec = iovec { iov_base: data_ptr as *mut c_void, iov_len: len as u64, }; let iov_ptr: *mut iovec = &mut iov as *mut iovec; let msg: msghdr = msghdr { msg_name: sockaddr_ptr as *mut c_void, msg_namelen: addrlen as u32, msg_iov: iov_ptr, msg_iovlen: 1, msg_control: ptr::null_mut() as *mut _, msg_controllen: 0, msg_flags: 0, }; liburing::io_uring_prep_sendmsg(sqe, sockfd, &msg, 0); if liburing::io_uring_submit(io_uring) < 1 { return Err(Fail::new(libc::EAGAIN, "failed to submit push operation")); } } Ok(data_ptr as u64) } pub fn pop(&mut self, sockfd: RawFd, buf: DataBuffer) -> Result<u64, Fail> { let len: usize = buf.len(); let data: &[u8] = &buf[..]; let data_ptr: *const u8 = data.as_ptr(); let io_uring: &mut io_uring = &mut self.io_uring; unsafe { let sqe: *mut io_uring_sqe = liburing::io_uring_get_sqe(io_uring); if sqe.is_null() { let errno: i32 = errno::errno(); let strerror: CString = CString::from_raw(libc::strerror(errno)); let cause: &str = strerror.to_str().unwrap_or("failed to get sqe"); return Err(Fail::new(errno, cause)); } liburing::io_uring_sqe_set_data(sqe, data_ptr as *mut c_void); liburing::io_uring_prep_recv(sqe, sockfd, data_ptr as *mut c_void, len, 0); if liburing::io_uring_submit(io_uring) < 1 { return Err(Fail::new(libc::EAGAIN, "failed to submit pop operation")); } Ok(data_ptr as u64) } } pub fn wait(&mut self) -> Result<(u64, i32), Fail> { let io_uring: &mut io_uring = &mut self.io_uring; unsafe { let mut cqe_ptr: *mut liburing::io_uring_cqe = null_mut(); let cqe_ptr_ptr: *mut *mut liburing::io_uring_cqe = ptr::addr_of_mut!(cqe_ptr); let wait_nr: c_int = liburing::io_uring_wait_cqe(io_uring, cqe_ptr_ptr); if wait_nr < 0 { let errno: i32 = -wait_nr; warn!("io_uring_wait_cqe() failed ({:?})", errno); return Err(Fail::new(errno, "operation in progress")); } else if wait_nr == 0 { let size: i32 = (*cqe_ptr).res; let buf_addr: u64 = liburing::io_uring_cqe_get_data(cqe_ptr) as u64; liburing::io_uring_cqe_seen(io_uring, cqe_ptr); return Ok((buf_addr, size)); } } unreachable!("should not happen") } }
use crate::demikernel::dbuf::DataBuffer; use ::libc::socklen_t; use ::liburing::{ io_uring, io_uring_sqe, iovec, msghdr, }; use ::nix::{ errno, sys::socket::SockAddr, }; use ::runtime::fail::Fail; use ::std::{ ffi::{ c_void, CString, }, mem::MaybeUninit, os::{ raw::c_int, unix::prelude::RawFd, }, ptr::{ self, null_mut, }, }; pub struct IoUring { io_uring: io_uring, } impl IoUring { pub fn new(nentries: u32) -> Result<Self, Fail> { unsafe { let mut params: MaybeUninit<liburing::io_uring_params> = MaybeUninit::zeroed(); let mut io_uring: MaybeUninit<io_uring> = MaybeUninit::zeroed(); let ret: c_int = liburing::io_uring_queue_init_params(nentries, io_uring.as_mut_ptr(), params.as_mut_ptr()); if ret < 0 { let errno: i32 = -ret; let strerror: CString = CString::from_raw(libc::strerror(errno)); let cause: &str = strerror.to_str().unwrap_or("failed to initialize io_uring"); return Err(Fail::new(errno, cause)); } Ok(Self { io_uring: io_uring.assume_init(), }) } } pub fn push(&mut self, sockfd: RawFd, buf: DataBuffer) -> Result<u64, Fai
pub fn pushto(&mut self, sockfd: RawFd, addr: SockAddr, buf: DataBuffer) -> Result<u64, Fail> { let len: usize = buf.len(); let data: &[u8] = &buf[..]; let data_ptr: *const u8 = data.as_ptr(); let (sockaddr, addrlen): (&libc::sockaddr, socklen_t) = addr.as_ffi_pair(); let sockaddr_ptr: *const libc::sockaddr = sockaddr as *const libc::sockaddr; let io_uring: &mut io_uring = &mut self.io_uring; unsafe { let sqe: *mut io_uring_sqe = liburing::io_uring_get_sqe(io_uring); if sqe.is_null() { let errno: i32 = errno::errno(); let strerror: CString = CString::from_raw(libc::strerror(errno)); let cause: &str = strerror.to_str().unwrap_or("failed to get sqe"); return Err(Fail::new(errno, cause)); } liburing::io_uring_sqe_set_data(sqe, data_ptr as *mut c_void); let mut iov: iovec = iovec { iov_base: data_ptr as *mut c_void, iov_len: len as u64, }; let iov_ptr: *mut iovec = &mut iov as *mut iovec; let msg: msghdr = msghdr { msg_name: sockaddr_ptr as *mut c_void, msg_namelen: addrlen as u32, msg_iov: iov_ptr, msg_iovlen: 1, msg_control: ptr::null_mut() as *mut _, msg_controllen: 0, msg_flags: 0, }; liburing::io_uring_prep_sendmsg(sqe, sockfd, &msg, 0); if liburing::io_uring_submit(io_uring) < 1 { return Err(Fail::new(libc::EAGAIN, "failed to submit push operation")); } } Ok(data_ptr as u64) } pub fn pop(&mut self, sockfd: RawFd, buf: DataBuffer) -> Result<u64, Fail> { let len: usize = buf.len(); let data: &[u8] = &buf[..]; let data_ptr: *const u8 = data.as_ptr(); let io_uring: &mut io_uring = &mut self.io_uring; unsafe { let sqe: *mut io_uring_sqe = liburing::io_uring_get_sqe(io_uring); if sqe.is_null() { let errno: i32 = errno::errno(); let strerror: CString = CString::from_raw(libc::strerror(errno)); let cause: &str = strerror.to_str().unwrap_or("failed to get sqe"); return Err(Fail::new(errno, cause)); } liburing::io_uring_sqe_set_data(sqe, data_ptr as *mut c_void); liburing::io_uring_prep_recv(sqe, sockfd, data_ptr as *mut c_void, len, 0); if liburing::io_uring_submit(io_uring) < 1 { return Err(Fail::new(libc::EAGAIN, "failed to submit pop operation")); } Ok(data_ptr as u64) } } pub fn wait(&mut self) -> Result<(u64, i32), Fail> { let io_uring: &mut io_uring = &mut self.io_uring; unsafe { let mut cqe_ptr: *mut liburing::io_uring_cqe = null_mut(); let cqe_ptr_ptr: *mut *mut liburing::io_uring_cqe = ptr::addr_of_mut!(cqe_ptr); let wait_nr: c_int = liburing::io_uring_wait_cqe(io_uring, cqe_ptr_ptr); if wait_nr < 0 { let errno: i32 = -wait_nr; warn!("io_uring_wait_cqe() failed ({:?})", errno); return Err(Fail::new(errno, "operation in progress")); } else if wait_nr == 0 { let size: i32 = (*cqe_ptr).res; let buf_addr: u64 = liburing::io_uring_cqe_get_data(cqe_ptr) as u64; liburing::io_uring_cqe_seen(io_uring, cqe_ptr); return Ok((buf_addr, size)); } } unreachable!("should not happen") } }
l> { let len: usize = buf.len(); let data: &[u8] = &buf[..]; let data_ptr: *const u8 = data.as_ptr(); let io_uring: &mut io_uring = &mut self.io_uring; unsafe { let sqe: *mut io_uring_sqe = liburing::io_uring_get_sqe(io_uring); if sqe.is_null() { let errno: i32 = errno::errno(); let strerror: CString = CString::from_raw(libc::strerror(errno)); let cause: &str = strerror.to_str().unwrap_or("failed to get sqe"); return Err(Fail::new(errno, cause)); } liburing::io_uring_sqe_set_data(sqe, data_ptr as *mut c_void); liburing::io_uring_prep_send(sqe, sockfd, data_ptr as *const c_void, len, 0); if liburing::io_uring_submit(io_uring) < 1 { return Err(Fail::new(libc::EAGAIN, "failed to submit push operation")); } } Ok(data_ptr as u64) }
function_block-function_prefixed
[ { "content": "fn with_libos<T>(f: impl FnOnce(&mut LibOS) -> T) -> T {\n\n LIBOS.with(|l| {\n\n let mut tls_libos: RefMut<Option<LibOS>> = l.borrow_mut();\n\n f(tls_libos.as_mut().expect(\"Uninitialized engine\"))\n\n })\n\n}\n\n\n\n//=========================================================...
Rust
src/complex/myanmar_machine.rs
ebraminio/rustybuzz
07d9419d04d956d3f588b547dcd2b36576504c6e
use crate::Buffer; const MACHINE_TRANS_KEYS: &[u8] = &[ 1, 32, 3, 30, 5, 29, 5, 8, 5, 29, 3, 25, 5, 25, 5, 25, 3, 29, 3, 29, 3, 29, 3, 29, 1, 16, 3, 29, 3, 29, 3, 29, 3, 29, 3, 29, 3, 30, 3, 29, 3, 29, 3, 29, 3, 29, 3, 29, 5, 29, 5, 8, 5, 29, 3, 25, 5, 25, 5, 25, 3, 29, 3, 29, 3, 29, 3, 29, 1, 16, 3, 30, 3, 29, 3, 29, 3, 29, 3, 29, 3, 29, 3, 30, 3, 29, 3, 29, 3, 29, 3, 29, 3, 29, 3, 30, 3, 29, 1, 32, 1, 32, 8, 8, 0 ]; const MACHINE_KEY_SPANS: &[u8] = &[ 32, 28, 25, 4, 25, 23, 21, 21, 27, 27, 27, 27, 16, 27, 27, 27, 27, 27, 28, 27, 27, 27, 27, 27, 25, 4, 25, 23, 21, 21, 27, 27, 27, 27, 16, 28, 27, 27, 27, 27, 27, 28, 27, 27, 27, 27, 27, 28, 27, 32, 32, 1 ]; const MACHINE_INDEX_OFFSETS: &[u16] = &[ 0, 33, 62, 88, 93, 119, 143, 165, 187, 215, 243, 271, 299, 316, 344, 372, 400, 428, 456, 485, 513, 541, 569, 597, 625, 651, 656, 682, 706, 728, 750, 778, 806, 834, 862, 879, 908, 936, 964, 992, 1020, 1048, 1077, 1105, 1133, 1161, 1189, 1217, 1246, 1274, 1307, 1340 ]; const MACHINE_INDICIES: &[u8] = &[ 1, 1, 2, 3, 4, 4, 0, 5, 0, 6, 1, 0, 0, 0, 0, 7, 0, 8, 9, 0, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 1, 0, 22, 23, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 27, 21, 21, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 21, 24, 24, 21, 25, 21, 21, 21, 21, 21, 21, 21, 21, 21, 38, 21, 21, 21, 21, 21, 21, 32, 21, 21, 21, 36, 21, 24, 24, 21, 25, 21, 24, 24, 21, 25, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 32, 21, 21, 21, 36, 21, 39, 21, 24, 24, 21, 25, 21, 32, 21, 21, 21, 21, 21, 21, 21, 40, 21, 21, 21, 21, 21, 21, 32, 21, 24, 24, 21, 25, 21, 21, 21, 21, 21, 21, 21, 21, 21, 40, 21, 21, 21, 21, 21, 21, 32, 21, 24, 24, 21, 25, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 32, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 41, 21, 21, 41, 21, 21, 21, 32, 42, 21, 21, 36, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 32, 21, 21, 21, 36, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 41, 21, 21, 21, 21, 21, 21, 32, 42, 21, 21, 36, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 32, 42, 21, 21, 36, 21, 1, 1, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 1, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 27, 21, 21, 28, 29, 30, 31, 32, 33, 34, 35, 36, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 43, 21, 21, 21, 21, 21, 21, 32, 33, 34, 35, 36, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 32, 33, 34, 35, 36, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 32, 33, 34, 21, 36, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 32, 21, 34, 21, 36, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 32, 33, 34, 35, 36, 43, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 28, 21, 30, 21, 32, 33, 34, 35, 36, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 43, 21, 21, 28, 21, 21, 21, 32, 33, 34, 35, 36, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 44, 21, 21, 28, 29, 30, 21, 32, 33, 34, 35, 36, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 28, 29, 30, 21, 32, 33, 34, 35, 36, 21, 22, 23, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 27, 21, 21, 28, 29, 30, 31, 32, 33, 34, 35, 36, 21, 46, 46, 45, 5, 45, 45, 45, 45, 45, 45, 45, 45, 45, 47, 45, 45, 45, 45, 45, 45, 14, 45, 45, 45, 18, 45, 46, 46, 45, 5, 45, 46, 46, 45, 5, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 14, 45, 45, 45, 18, 45, 48, 45, 46, 46, 45, 5, 45, 14, 45, 45, 45, 45, 45, 45, 45, 49, 45, 45, 45, 45, 45, 45, 14, 45, 46, 46, 45, 5, 45, 45, 45, 45, 45, 45, 45, 45, 45, 49, 45, 45, 45, 45, 45, 45, 14, 45, 46, 46, 45, 5, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 14, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 50, 45, 45, 50, 45, 45, 45, 14, 51, 45, 45, 18, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 14, 45, 45, 45, 18, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 50, 45, 45, 45, 45, 45, 45, 14, 51, 45, 45, 18, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 14, 51, 45, 45, 18, 45, 52, 52, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 52, 45, 2, 3, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 8, 45, 45, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 8, 45, 45, 10, 11, 12, 13, 14, 15, 16, 17, 18, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 53, 45, 45, 45, 45, 45, 45, 14, 15, 16, 17, 18, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 14, 15, 16, 17, 18, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 14, 15, 16, 45, 18, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 14, 45, 16, 45, 18, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 14, 15, 16, 17, 18, 53, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 10, 45, 12, 45, 14, 15, 16, 17, 18, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 53, 45, 45, 10, 45, 45, 45, 14, 15, 16, 17, 18, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 54, 45, 45, 10, 11, 12, 45, 14, 15, 16, 17, 18, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 10, 11, 12, 45, 14, 15, 16, 17, 18, 45, 2, 3, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 8, 45, 45, 10, 11, 12, 13, 14, 15, 16, 17, 18, 45, 22, 23, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 55, 21, 21, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 21, 22, 56, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 27, 21, 21, 28, 29, 30, 31, 32, 33, 34, 35, 36, 21, 1, 1, 2, 3, 46, 46, 45, 5, 45, 6, 1, 45, 45, 45, 45, 1, 45, 8, 45, 45, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 45, 1, 45, 1, 1, 57, 57, 57, 57, 57, 57, 57, 57, 1, 57, 57, 57, 57, 1, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 1, 57, 58, 57, 0 ]; const MACHINE_TRANS_TARGS: &[u8] = &[ 0, 1, 24, 34, 0, 25, 31, 47, 36, 50, 37, 42, 43, 44, 27, 39, 40, 41, 30, 46, 51, 0, 2, 12, 0, 3, 9, 13, 14, 19, 20, 21, 5, 16, 17, 18, 8, 23, 4, 6, 7, 10, 11, 15, 22, 0, 0, 26, 28, 29, 32, 33, 35, 38, 45, 48, 49, 0, 0 ]; const MACHINE_TRANS_ACTIONS: &[u8] = &[ 3, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 10 ]; const MACHINE_TO_STATE_ACTIONS: &[u8] = &[ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; const MACHINE_FROM_STATE_ACTIONS: &[u8] = &[ 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; const MACHINE_EOF_TRANS: &[u8] = &[ 0, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 22, 22, 46, 58, 58 ]; #[derive(Clone, Copy)] pub enum SyllableType { ConsonantSyllable = 0, PunctuationCluster, BrokenCluster, NonMyanmarCluster, } pub fn find_syllables_myanmar(buffer: &mut Buffer) { let mut cs = 0usize; let mut ts = 0; let mut te; let mut p = 0; let pe = buffer.len(); let eof = buffer.len(); let mut syllable_serial = 1u8; let mut reset = true; let mut slen; let mut trans = 0; if p == pe { if MACHINE_EOF_TRANS[cs] > 0 { trans = (MACHINE_EOF_TRANS[cs] - 1) as usize; } } loop { if reset { if MACHINE_FROM_STATE_ACTIONS[cs] == 2 { ts = p; } slen = MACHINE_KEY_SPANS[cs] as usize; let cs_idx = ((cs as i32) << 1) as usize; let i = if slen > 0 && MACHINE_TRANS_KEYS[cs_idx] <= buffer.info[p].indic_category() as u8 && buffer.info[p].indic_category() as u8 <= MACHINE_TRANS_KEYS[cs_idx + 1] { (buffer.info[p].indic_category() as u8 - MACHINE_TRANS_KEYS[cs_idx]) as usize } else { slen }; trans = MACHINE_INDICIES[MACHINE_INDEX_OFFSETS[cs] as usize + i] as usize; } reset = true; cs = MACHINE_TRANS_TARGS[trans] as usize; if MACHINE_TRANS_ACTIONS[trans] != 0 { match MACHINE_TRANS_ACTIONS[trans] { 6 => { te = p + 1; found_syllable(ts, te, &mut syllable_serial, SyllableType::ConsonantSyllable, buffer); } 4 => { te = p + 1; found_syllable(ts, te, &mut syllable_serial, SyllableType::NonMyanmarCluster, buffer); } 10 => { te = p + 1; found_syllable(ts, te, &mut syllable_serial, SyllableType::PunctuationCluster, buffer); } 8 => { te = p + 1; found_syllable(ts, te, &mut syllable_serial, SyllableType::BrokenCluster, buffer); } 3 => { te = p + 1; found_syllable(ts, te, &mut syllable_serial, SyllableType::NonMyanmarCluster, buffer); } 5 => { te = p; p -= 1; found_syllable(ts, te, &mut syllable_serial, SyllableType::ConsonantSyllable, buffer); } 7 => { te = p; p -= 1; found_syllable(ts, te, &mut syllable_serial, SyllableType::BrokenCluster, buffer); } 9 => { te = p; p -= 1; found_syllable(ts, te, &mut syllable_serial, SyllableType::NonMyanmarCluster, buffer); } _ => {} } } if MACHINE_TO_STATE_ACTIONS[cs] == 1 { ts = 0; } p += 1; if p != pe { continue; } if p == eof { if MACHINE_EOF_TRANS[cs] > 0 { trans = (MACHINE_EOF_TRANS[cs] - 1) as usize; reset = false; continue; } } break; } } #[inline] fn found_syllable( start: usize, end: usize, syllable_serial: &mut u8, kind: SyllableType, buffer: &mut Buffer, ) { for i in start..end { buffer.info[i].set_syllable((*syllable_serial << 4) | kind as u8); } *syllable_serial += 1; if *syllable_serial == 16 { *syllable_serial = 1; } }
use crate::Buffer; const MACHINE_TRANS_KEYS: &[u8] = &[ 1, 32, 3, 30, 5, 29, 5, 8, 5, 29, 3, 25, 5, 25, 5, 25, 3, 29, 3, 29, 3, 29, 3, 29, 1, 16, 3, 29, 3, 29, 3, 29, 3, 29, 3, 29, 3, 30, 3, 29, 3, 29, 3, 29, 3, 29, 3, 29, 5, 29, 5, 8, 5, 29, 3, 25, 5, 25, 5, 25, 3, 29, 3, 29, 3, 29, 3, 29, 1, 16, 3, 30, 3, 29, 3, 29, 3, 29, 3, 29, 3, 29, 3, 30, 3, 29, 3, 29, 3, 29, 3, 29, 3, 29, 3, 30, 3, 29, 1, 32, 1, 32, 8, 8, 0 ]; const MACHINE_KEY_SPANS: &[u8] = &[ 32, 28, 25, 4, 25, 23, 21, 21, 27, 27, 27, 27, 16, 27, 27, 27, 27, 27, 28, 27, 27, 27, 27, 27, 25, 4, 25, 23, 21, 21, 27, 27, 27, 27, 16, 28, 27, 27, 27, 27, 27, 28, 27, 27, 27, 27, 27, 28, 27, 32, 32, 1 ]; const MACHINE_INDEX_OFFSETS: &[u16] = &[ 0, 33, 62, 88, 93, 119, 143, 165, 187, 215, 243, 271, 299, 316, 344, 372, 400, 428, 456, 485, 513, 541, 569, 597, 625, 651, 656, 682, 706, 728, 750, 778, 806, 834, 862, 879, 908, 936, 964, 992, 1020, 1048, 1077, 1105, 1133, 1161, 1189, 1217, 1246, 1274, 1307, 1340 ]; const MACHINE_INDICIES: &[u8] = &[ 1, 1, 2, 3, 4, 4, 0, 5, 0, 6, 1, 0, 0, 0, 0, 7, 0, 8, 9, 0, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 1, 0, 22, 23, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 27, 21, 21, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 21, 24, 24, 21, 25, 21, 21, 21, 21, 21, 21, 21, 21, 21, 38, 21, 21, 21, 21, 21, 21, 32, 21, 21, 21, 36, 21, 24, 24, 21, 25, 21, 24, 24, 21, 25, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 32, 21, 21, 21, 36, 21, 39, 21, 24, 24, 21, 25, 21, 32, 21, 21, 21, 21, 21, 21, 21, 40, 21, 21, 21, 21, 21, 21, 32, 21, 24, 24, 21, 25, 21, 21, 21, 21, 21, 21, 21, 21, 21, 40, 21, 21, 21, 21, 21, 21, 32, 21, 24, 24, 21, 25, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 32, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 41, 21, 21, 41, 21, 21, 21, 32, 42, 21, 21, 36, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 32, 21, 21, 21, 36, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 41, 21, 21, 21, 21, 21, 21, 32, 42, 21, 21, 36, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 32, 42, 21, 21, 36, 21, 1, 1, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 1, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 27, 21, 21, 28, 29, 30, 31, 32, 33, 34, 35, 36, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 43, 21, 21, 21, 21, 21, 21, 32, 33, 34, 35, 36, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 32, 33, 34, 35, 36, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 32, 33, 34, 21, 36, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 32, 21, 34, 21, 36, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 32, 33, 34, 35, 36, 43, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 28, 21, 30, 21, 32, 33, 34, 35, 36, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 43, 21, 21, 28, 21, 21, 21, 32, 33, 34, 35, 36, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 44, 21, 21, 28, 29, 30, 21, 32, 33, 34, 35, 36, 21, 22, 21, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 28, 29, 30, 21, 32, 33, 34, 35, 36, 21, 22, 23, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 27, 21, 21, 28, 29, 30, 31, 32, 33, 34, 35, 36, 21, 46, 46, 45, 5, 45, 45, 45, 45, 45, 45, 45, 45, 45, 47, 45, 45, 45, 45, 45, 45, 14, 45, 45, 45, 18, 45, 46, 46, 45, 5, 45, 46, 46, 45, 5, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 14, 45, 45, 45, 18, 45, 48, 45, 46, 46, 45, 5, 45, 14, 45, 45, 45, 45, 45, 45, 45, 49, 45, 45, 45, 45, 45, 45, 14, 45, 46, 46, 45, 5, 45, 45, 45, 45, 45, 45, 45, 45, 45, 49, 45, 45, 45, 45, 45, 45, 14, 45, 46, 46, 45, 5, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 14, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 50, 45, 45, 50, 45, 45, 45, 14, 51, 45, 45, 18, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 14, 45, 45, 45, 18, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 50, 45, 45, 45, 45, 45, 45, 14, 51, 45, 45, 18, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 14, 51, 45, 45, 18, 45, 52, 52, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 52, 45, 2, 3, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 8, 45, 45, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 8, 45, 45, 10, 11, 12, 13, 14, 15, 16, 17, 18, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 53, 45, 45, 45, 45, 45, 45, 14, 15, 16, 17, 18, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 14, 15, 16, 17, 18, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 14, 15, 16, 45, 18, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 14, 45, 16, 45, 18, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 14, 15, 16, 17, 18, 53, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 10, 45, 12, 45, 14, 15, 16, 17, 18, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 53, 45, 45, 10, 45, 45, 45, 14, 15, 16, 17, 18, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 54, 45, 45, 10, 11, 12, 45, 14, 15, 16, 17, 18, 45, 2, 45, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 10, 11, 12, 45, 14, 15, 16, 17, 18, 45, 2, 3, 46, 46, 45, 5, 45, 6, 45, 45, 45, 45, 45, 45, 45, 8, 45, 45, 10, 11, 12, 13, 14, 15, 16, 17, 18, 45, 22, 23, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 55, 21, 21, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 21, 22, 56, 24, 24, 21, 25, 21, 26, 21, 21, 21, 21, 21, 21, 21, 27, 21, 21, 28, 29, 30, 31, 32, 33, 34, 35, 36, 21, 1, 1, 2, 3, 46, 46, 45, 5, 45, 6, 1, 45, 45, 45, 45, 1, 45, 8, 45, 45, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 45, 1, 45, 1, 1, 57, 57, 57, 57, 57, 57, 57, 57, 1, 57, 57, 57, 57, 1, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 1, 57, 58, 57, 0 ]; const MACHINE_TRANS_TARGS: &[u8] = &[ 0, 1, 24, 34, 0, 25, 31, 47, 36, 50, 37, 42, 43, 44, 27, 39, 40, 41, 30, 46, 51, 0, 2, 12, 0, 3, 9, 13, 14, 19, 20, 21, 5, 16, 17, 18, 8, 23, 4, 6, 7, 10, 11, 15, 22, 0, 0, 26, 28, 29, 32, 33, 35, 38, 45, 48, 49, 0, 0 ]; const MACHINE_TRANS_ACTIONS: &[u8] = &[ 3, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 10 ]; const MACHINE_TO_STATE_ACTIONS: &[u8] = &[ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; const MACHINE_FROM_STATE_ACTIONS: &[u8] = &[ 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; const MACHINE_EOF_TRANS: &[u8] = &[ 0, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 22, 22, 46, 58, 58 ]; #[derive(Clone, Copy)] pub enum SyllableType { ConsonantSyllable = 0, PunctuationCluster, BrokenCluster, NonMyanmarCluster, } pub fn find_syllables_myanmar(buffer: &mut Buffer) { let mut cs = 0usize; let mut ts = 0; let mut te; let mut p = 0; let pe = buffer.len(); let eof = buffer.len(); let mut syllable_serial = 1u8; let mut reset = true; let mut slen; let mut trans = 0; if p == pe { if MACHINE_EOF_TRANS[cs] > 0 { trans = (MACHINE_EOF_TRANS[cs] - 1) as usize; } } loop { if reset { if MACHINE_FROM_STATE_ACTIONS[cs] == 2 { ts = p; } slen = MACHINE_KEY_SPANS[cs] as usize; let cs_idx = ((cs as i32) << 1) as usize; let i = if slen > 0 && MACHINE_TRANS_KEYS[cs_idx] <= buffer.info[p].indic_category() as u8 && buffer.info[p].indic_category() as u8 <= MACHINE_TRANS_KEYS[cs_idx + 1] { (buffer.info[p].indic_category() as u8 - MACHINE_TRANS_KEYS[cs_idx]) as usize } else { slen }; trans = MACHINE_INDICIES[MACHINE_INDEX_OFFSETS[cs] as usize + i] as usize; } reset = true; cs = MACHINE_TRANS_TARGS[trans] as usize; if MACHINE_TRANS_ACTIONS[trans] != 0 { match MACHINE_TRANS_ACTIONS[trans] { 6 => { te = p + 1; found_syllable(ts, te, &mut syllable_serial, SyllableType::ConsonantSyllable, buffer); } 4 => { te = p + 1; found_syllable(ts, te, &mut syllable_serial, SyllableType::NonMyanmarCluster, buffer); } 10 => { te = p + 1; found_syllable(ts, te, &mut syllable_serial, SyllableType::PunctuationCluster, buffer); } 8 => { te = p + 1; found_syllable(ts, te, &mut syllable_serial, SyllableType::BrokenCluster, buffer); } 3 => { te = p + 1; found_syllable(ts, te, &mut syllable_serial, SyllableType::NonMyanmarCluster, buffer); } 5 => { te = p; p -= 1; found_syllable(ts, te, &mut syllable_serial, SyllableType::ConsonantSyllable, buffer); } 7 => { te = p; p -= 1; found_syllable(ts, te, &mut syllable_serial, SyllableType::BrokenCluster, buffer); } 9 => { te = p; p -= 1; found_syllable(ts, te, &mut syllable_serial, SyllableType::NonMyanmarCluster, buffer); } _ => {} } } if MACHINE_TO_STATE_ACTIONS[cs] == 1 { ts = 0; } p += 1; if p != pe { continue; } if p == eof { if MACHINE_EOF_TRANS[cs] > 0 { trans = (MACHINE_EOF_TRANS[cs] - 1) as usize; reset = false; continue; } } break; } } #[inline] fn
*syllable_serial = 1; } }
found_syllable( start: usize, end: usize, syllable_serial: &mut u8, kind: SyllableType, buffer: &mut Buffer, ) { for i in start..end { buffer.info[i].set_syllable((*syllable_serial << 4) | kind as u8); } *syllable_serial += 1; if *syllable_serial == 16 {
function_block-random_span
[ { "content": "pub fn find_syllables(buffer: &mut Buffer) {\n\n let mut cs = 5usize;\n\n let mut ts = 0;\n\n let mut te = 0;\n\n let mut act = 0;\n\n let mut p = 0;\n\n let pe = buffer.len();\n\n let eof = buffer.len();\n\n let mut syllable_serial = 1u8;\n\n let mut reset = true;\n\n ...
Rust
garnet/bin/power_manager/src/temperature_handler.rs
zarelaky/fuchsia
858cc1914de722b13afc2aaaee8a6bd491cd8d9a
use crate::error::PowerManagerError; use crate::log_if_err; use crate::message::{Message, MessageReturn}; use crate::node::Node; use crate::types::Celsius; use crate::utils::connect_proxy; use anyhow::{format_err, Error}; use async_trait::async_trait; use fidl_fuchsia_hardware_thermal as fthermal; use fuchsia_inspect::{self as inspect, NumericProperty, Property}; use fuchsia_inspect_contrib::{inspect_log, nodes::BoundedListNode}; use fuchsia_syslog::fx_log_err; use fuchsia_zircon as zx; use std::cell::RefCell; use std::rc::Rc; pub struct TemperatureHandlerBuilder<'a> { driver_path: String, driver_proxy: Option<fthermal::DeviceProxy>, inspect_root: Option<&'a inspect::Node>, } impl<'a> TemperatureHandlerBuilder<'a> { pub fn new_with_driver_path(driver_path: String) -> Self { Self { driver_path, driver_proxy: None, inspect_root: None } } #[cfg(test)] pub fn new_with_proxy(driver_path: String, proxy: fthermal::DeviceProxy) -> Self { Self { driver_path, driver_proxy: Some(proxy), inspect_root: None } } #[cfg(test)] pub fn with_inspect_root(mut self, root: &'a inspect::Node) -> Self { self.inspect_root = Some(root); self } pub fn build(self) -> Result<Rc<TemperatureHandler>, Error> { let proxy = if self.driver_proxy.is_none() { connect_proxy::<fthermal::DeviceMarker>(&self.driver_path)? } else { self.driver_proxy.unwrap() }; let inspect_root = self.inspect_root.unwrap_or(inspect::component::inspector().root()); Ok(Rc::new(TemperatureHandler { driver_path: self.driver_path.clone(), driver_proxy: proxy, inspect: InspectData::new( inspect_root, format!("TemperatureHandler ({})", self.driver_path), ), })) } } pub struct TemperatureHandler { driver_path: String, driver_proxy: fthermal::DeviceProxy, inspect: InspectData, } impl TemperatureHandler { async fn handle_read_temperature(&self) -> Result<MessageReturn, PowerManagerError> { fuchsia_trace::duration!( "power_manager", "TemperatureHandler::handle_read_temperature", "driver" => self.driver_path.as_str() ); let result = self.read_temperature().await; log_if_err!( result, format!("Failed to read temperature from {}", self.driver_path).as_str() ); fuchsia_trace::instant!( "power_manager", "TemperatureHandler::read_temperature_result", fuchsia_trace::Scope::Thread, "driver" => self.driver_path.as_str(), "result" => format!("{:?}", result).as_str() ); if result.is_ok() { self.inspect.log_temperature_reading(*result.as_ref().unwrap()) } else { self.inspect.read_errors.add(1); self.inspect.last_read_error.set(format!("{}", result.as_ref().unwrap_err()).as_str()); } Ok(MessageReturn::ReadTemperature(result?)) } async fn read_temperature(&self) -> Result<Celsius, Error> { fuchsia_trace::duration!( "power_manager", "TemperatureHandler::read_temperature", "driver" => self.driver_path.as_str() ); let (status, temperature) = self.driver_proxy.get_temperature_celsius().await.map_err(|e| { format_err!( "{} ({}): get_temperature_celsius IPC failed: {}", self.name(), self.driver_path, e ) })?; zx::Status::ok(status).map_err(|e| { format_err!( "{} ({}): get_temperature_celsius driver returned error: {}", self.name(), self.driver_path, e ) })?; Ok(Celsius(temperature.into())) } } #[async_trait(?Send)] impl Node for TemperatureHandler { fn name(&self) -> &'static str { "TemperatureHandler" } async fn handle_message(&self, msg: &Message) -> Result<MessageReturn, PowerManagerError> { match msg { Message::ReadTemperature => self.handle_read_temperature().await, _ => Err(PowerManagerError::Unsupported), } } } const NUM_INSPECT_TEMPERATURE_SAMPLES: usize = 10; struct InspectData { temperature_readings: RefCell<BoundedListNode>, read_errors: inspect::UintProperty, last_read_error: inspect::StringProperty, } impl InspectData { fn new(parent: &inspect::Node, name: String) -> Self { let root = parent.create_child(name); let temperature_readings = RefCell::new(BoundedListNode::new( root.create_child("temperature_readings"), NUM_INSPECT_TEMPERATURE_SAMPLES, )); let read_errors = root.create_uint("read_temperature_error_count", 0); let last_read_error = root.create_string("last_read_error", ""); parent.record(root); InspectData { temperature_readings, read_errors, last_read_error } } fn log_temperature_reading(&self, temperature: Celsius) { inspect_log!(self.temperature_readings.borrow_mut(), temperature: temperature.0); } } #[cfg(test)] pub mod tests { use super::*; use fuchsia_async as fasync; use futures::TryStreamExt; use inspect::assert_inspect_tree; fn setup_fake_driver( mut get_temperature: impl FnMut() -> Celsius + 'static, ) -> fthermal::DeviceProxy { let (proxy, mut stream) = fidl::endpoints::create_proxy_and_stream::<fthermal::DeviceMarker>().unwrap(); fasync::spawn_local(async move { while let Ok(req) = stream.try_next().await { match req { Some(fthermal::DeviceRequest::GetTemperatureCelsius { responder }) => { let _ = responder.send(zx::Status::OK.into_raw(), get_temperature().0 as f32); } _ => assert!(false), } } }); proxy } pub fn setup_test_node( get_temperature: impl FnMut() -> Celsius + 'static, ) -> Rc<TemperatureHandler> { TemperatureHandlerBuilder::new_with_proxy( "Fake".to_string(), setup_fake_driver(get_temperature), ) .build() .unwrap() } #[fasync::run_singlethreaded(test)] async fn test_read_temperature() { let temperature_readings = vec![1.2, 3.4, 5.6, 7.8, 9.0]; let expected_readings: Vec<f64> = temperature_readings.iter().map(|x| *x as f32 as f64).collect(); let mut index = 0; let get_temperature = move || { let value = temperature_readings[index]; index = (index + 1) % temperature_readings.len(); Celsius(value) }; let node = setup_test_node(get_temperature); for expected_reading in expected_readings { let result = node.handle_message(&Message::ReadTemperature).await; let temperature = result.unwrap(); if let MessageReturn::ReadTemperature(t) = temperature { assert_eq!(t.0, expected_reading); } else { assert!(false); } } } #[fasync::run_singlethreaded(test)] async fn test_unsupported_msg() { let node = setup_test_node(|| Celsius(0.0)); match node.handle_message(&Message::GetTotalCpuLoad).await { Err(PowerManagerError::Unsupported) => {} e => panic!("Unexpected return value: {:?}", e), } } #[fasync::run_singlethreaded(test)] async fn test_inspect_data() { let temperature = Celsius(30.0); let inspector = inspect::Inspector::new(); let node = TemperatureHandlerBuilder::new_with_proxy( "Fake".to_string(), setup_fake_driver(move || temperature), ) .with_inspect_root(inspector.root()) .build() .unwrap(); node.handle_message(&Message::ReadTemperature).await.unwrap(); assert_inspect_tree!( inspector, root: { "TemperatureHandler (Fake)": contains { temperature_readings: { "0": { temperature: temperature.0, "@time": inspect::testing::AnyProperty } } } } ); } }
use crate::error::PowerManagerError; use crate::log_if_err; use crate::message::{Message, MessageReturn}; use crate::node::Node; use crate::types::Celsius; use crate::utils::connect_proxy; use anyhow::{format_err, Error}; use async_trait::async_trait; use fidl_fuchsia_hardware_thermal as fthermal; use fuchsia_inspect::{self as inspect, NumericProperty, Property}; use fuchsia_inspect_contrib::{inspect_log, nodes::BoundedListNode}; use fuchsia_syslog::fx_log_err; use fuchsia_zircon as zx; use std::cell::RefCell; use std::rc::Rc; pub struct TemperatureHandlerBuilder<'a> { driver_path: String, driver_proxy: Option<fthermal::DeviceProxy>, inspect_root: Option<&'a inspect::Node>, } impl<'a> TemperatureHandlerBuilder<'a> { pub fn new_with_driver_path(driver_path: String) -> Self { Self { driver_path, driver_proxy: None, inspect_root: None } } #[cfg(test)] pub fn new_with_proxy(driver_path: String, proxy: fthermal::DeviceProxy) -> Self { Self { driver_path, driver_proxy: Some(proxy), inspect_root: None } } #[cfg(test)] pub fn with_inspect_root(mut self, root: &'a inspect::Node) -> Self { self.inspect_root = Some(root); self } pub fn build(self) -> Result<Rc<TemperatureHandler>, Error> { let proxy = if self.driver_proxy.is_none() { connect_proxy::<fthermal::DeviceMarker>(&self.driver_path)? } else { self.driver_proxy.unwrap() }; let inspect_root = self.inspect_root.unwrap_or(inspect::component::inspector().root()); Ok(Rc::new(TemperatureHandler { driver_path: self.driver_path.clone(), driver_proxy: proxy, inspect: InspectData::new( inspect_root, format!("TemperatureHandler ({})", self.driver_path), ),
let node = TemperatureHandlerBuilder::new_with_proxy( "Fake".to_string(), setup_fake_driver(move || temperature), ) .with_inspect_root(inspector.root()) .build() .unwrap(); node.handle_message(&Message::ReadTemperature).await.unwrap(); assert_inspect_tree!( inspector, root: { "TemperatureHandler (Fake)": contains { temperature_readings: { "0": { temperature: temperature.0, "@time": inspect::testing::AnyProperty } } } } ); } }
})) } } pub struct TemperatureHandler { driver_path: String, driver_proxy: fthermal::DeviceProxy, inspect: InspectData, } impl TemperatureHandler { async fn handle_read_temperature(&self) -> Result<MessageReturn, PowerManagerError> { fuchsia_trace::duration!( "power_manager", "TemperatureHandler::handle_read_temperature", "driver" => self.driver_path.as_str() ); let result = self.read_temperature().await; log_if_err!( result, format!("Failed to read temperature from {}", self.driver_path).as_str() ); fuchsia_trace::instant!( "power_manager", "TemperatureHandler::read_temperature_result", fuchsia_trace::Scope::Thread, "driver" => self.driver_path.as_str(), "result" => format!("{:?}", result).as_str() ); if result.is_ok() { self.inspect.log_temperature_reading(*result.as_ref().unwrap()) } else { self.inspect.read_errors.add(1); self.inspect.last_read_error.set(format!("{}", result.as_ref().unwrap_err()).as_str()); } Ok(MessageReturn::ReadTemperature(result?)) } async fn read_temperature(&self) -> Result<Celsius, Error> { fuchsia_trace::duration!( "power_manager", "TemperatureHandler::read_temperature", "driver" => self.driver_path.as_str() ); let (status, temperature) = self.driver_proxy.get_temperature_celsius().await.map_err(|e| { format_err!( "{} ({}): get_temperature_celsius IPC failed: {}", self.name(), self.driver_path, e ) })?; zx::Status::ok(status).map_err(|e| { format_err!( "{} ({}): get_temperature_celsius driver returned error: {}", self.name(), self.driver_path, e ) })?; Ok(Celsius(temperature.into())) } } #[async_trait(?Send)] impl Node for TemperatureHandler { fn name(&self) -> &'static str { "TemperatureHandler" } async fn handle_message(&self, msg: &Message) -> Result<MessageReturn, PowerManagerError> { match msg { Message::ReadTemperature => self.handle_read_temperature().await, _ => Err(PowerManagerError::Unsupported), } } } const NUM_INSPECT_TEMPERATURE_SAMPLES: usize = 10; struct InspectData { temperature_readings: RefCell<BoundedListNode>, read_errors: inspect::UintProperty, last_read_error: inspect::StringProperty, } impl InspectData { fn new(parent: &inspect::Node, name: String) -> Self { let root = parent.create_child(name); let temperature_readings = RefCell::new(BoundedListNode::new( root.create_child("temperature_readings"), NUM_INSPECT_TEMPERATURE_SAMPLES, )); let read_errors = root.create_uint("read_temperature_error_count", 0); let last_read_error = root.create_string("last_read_error", ""); parent.record(root); InspectData { temperature_readings, read_errors, last_read_error } } fn log_temperature_reading(&self, temperature: Celsius) { inspect_log!(self.temperature_readings.borrow_mut(), temperature: temperature.0); } } #[cfg(test)] pub mod tests { use super::*; use fuchsia_async as fasync; use futures::TryStreamExt; use inspect::assert_inspect_tree; fn setup_fake_driver( mut get_temperature: impl FnMut() -> Celsius + 'static, ) -> fthermal::DeviceProxy { let (proxy, mut stream) = fidl::endpoints::create_proxy_and_stream::<fthermal::DeviceMarker>().unwrap(); fasync::spawn_local(async move { while let Ok(req) = stream.try_next().await { match req { Some(fthermal::DeviceRequest::GetTemperatureCelsius { responder }) => { let _ = responder.send(zx::Status::OK.into_raw(), get_temperature().0 as f32); } _ => assert!(false), } } }); proxy } pub fn setup_test_node( get_temperature: impl FnMut() -> Celsius + 'static, ) -> Rc<TemperatureHandler> { TemperatureHandlerBuilder::new_with_proxy( "Fake".to_string(), setup_fake_driver(get_temperature), ) .build() .unwrap() } #[fasync::run_singlethreaded(test)] async fn test_read_temperature() { let temperature_readings = vec![1.2, 3.4, 5.6, 7.8, 9.0]; let expected_readings: Vec<f64> = temperature_readings.iter().map(|x| *x as f32 as f64).collect(); let mut index = 0; let get_temperature = move || { let value = temperature_readings[index]; index = (index + 1) % temperature_readings.len(); Celsius(value) }; let node = setup_test_node(get_temperature); for expected_reading in expected_readings { let result = node.handle_message(&Message::ReadTemperature).await; let temperature = result.unwrap(); if let MessageReturn::ReadTemperature(t) = temperature { assert_eq!(t.0, expected_reading); } else { assert!(false); } } } #[fasync::run_singlethreaded(test)] async fn test_unsupported_msg() { let node = setup_test_node(|| Celsius(0.0)); match node.handle_message(&Message::GetTotalCpuLoad).await { Err(PowerManagerError::Unsupported) => {} e => panic!("Unexpected return value: {:?}", e), } } #[fasync::run_singlethreaded(test)] async fn test_inspect_data() { let temperature = Celsius(30.0); let inspector = inspect::Inspector::new();
random
[]
Rust
bin/engula.rs
mmyj/engula
84f5fa7b047b750fd84a0a2dcd4a698a5d21c077
use std::path::PathBuf; use clap::{crate_description, crate_version, Parser, Subcommand}; use engula_journal::{ file::Journal as FileJournal, grpc::Server as JournalServer, mem::Journal as MemJournal, }; use engula_kernel::grpc::{FileKernel, MemKernel, Server as KernelServer}; use engula_storage::{ file::Storage as FileStorage, grpc::Server as StorageServer, mem::Storage as MemStorage, }; use tokio::net::TcpListener; use tokio_stream::wrappers::TcpListenerStream; pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>; macro_rules! bootstrap_service { ($addr:expr, $server:expr) => {{ let listener = TcpListener::bind($addr).await?; tonic::transport::Server::builder() .add_service($server.into_service()) .serve_with_incoming(TcpListenerStream::new(listener)) .await?; }}; } #[derive(Subcommand)] enum RunMode { #[clap(name = "--mem", about = "Stores data in memory")] Mem, #[clap(name = "--file", about = "Stores data in local files")] File { #[clap(parse(from_os_str), about = "Path to store data")] path: PathBuf, }, } #[derive(Subcommand)] #[clap(about = "Commands to operate Storage")] enum StorageCommand { #[clap(about = "Run a storage server")] Run { #[clap(about = "Socket address to listen")] addr: String, #[clap(subcommand)] cmd: RunMode, }, } impl StorageCommand { async fn run(&self) -> Result<()> { match self { StorageCommand::Run { addr, cmd } => match cmd { RunMode::File { path } => { let storage = FileStorage::new(&path).await?; let server = StorageServer::new(storage); bootstrap_service!(addr, server); } RunMode::Mem => { let server = StorageServer::new(MemStorage::default()); bootstrap_service!(addr, server); } }, } Ok(()) } } #[derive(Subcommand)] #[clap(about = "Commands to operate Journal")] enum JournalCommand { #[clap(about = "Run a journal server")] Run { #[clap(about = "Socket address to listen")] addr: String, #[clap(subcommand)] cmd: RunMode, #[clap( long, default_value = "67108864", about = "The size of segments in bytes, only taking effects for a file instance" )] segment_size: usize, }, } impl JournalCommand { async fn run(&self) -> Result<()> { match self { JournalCommand::Run { addr, cmd, segment_size, } => match cmd { RunMode::File { path } => { let journal = FileJournal::open(path, *segment_size).await?; let server = JournalServer::new(journal); bootstrap_service!(addr, server); } RunMode::Mem => { let server = JournalServer::new(MemJournal::default()); bootstrap_service!(addr, server); } }, } Ok(()) } } #[derive(Subcommand)] #[clap(about = "Commands to operate Kernel")] enum KernelCommand { #[clap(about = "Run a kernel server")] Run { #[clap(about = "Socket address to listen")] addr: String, #[clap(subcommand)] mode: RunMode, #[clap(long, about = "The address of journal server")] journal: String, #[clap(long, about = "The address of storage server")] storage: String, }, } impl KernelCommand { async fn run(&self) -> Result<()> { match self { KernelCommand::Run { addr, mode: cmd, journal, storage, } => match cmd { RunMode::Mem => { let kernel = MemKernel::open(journal, storage).await?; let server = KernelServer::new(journal, storage, kernel); bootstrap_service!(addr, server); } RunMode::File { path } => { let kernel = FileKernel::open(journal, storage, &path).await?; let server = KernelServer::new(journal, storage, kernel); bootstrap_service!(addr, server); } }, } Ok(()) } } #[derive(Parser)] enum SubCommand { #[clap(subcommand)] Storage(StorageCommand), #[clap(subcommand)] Journal(JournalCommand), #[clap(subcommand)] Kernel(KernelCommand), } #[derive(Parser)] #[clap( version = crate_version!(), about = crate_description!(), )] struct Command { #[clap(subcommand)] subcmd: SubCommand, } impl Command { async fn run(&self) -> Result<()> { match &self.subcmd { SubCommand::Storage(cmd) => cmd.run().await?, SubCommand::Journal(cmd) => cmd.run().await?, SubCommand::Kernel(cmd) => cmd.run().await?, } Ok(()) } } #[tokio::main] async fn main() -> Result<()> { let cmd: Command = Command::parse(); cmd.run().await }
use std::path::PathBuf; use clap::{crate_description, crate_version, Parser, Subcommand}; use engula_journal::{ file::Journal as FileJournal, grpc::Server as JournalServer, mem::Journal as MemJournal, }; use engula_kernel::grpc::{FileKernel, MemKernel, Server as KernelServer}; use engula_storage::{ file::Storage as FileStorage, grpc::Server as StorageServer, mem::Storage as MemStorage, }; use tokio::net::TcpListener; use tokio_stream::wrappers::TcpListenerStream; pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>; macro_rules! bootstrap_service { ($addr:expr, $server:expr) => {{ let listener = TcpListener::bind($addr).await?; tonic::transport::Server::builder() .add_service($server.into_service()) .serve_with_incoming(TcpListenerStream::new(listener)) .await?; }}; } #[derive(Subcommand)] enum RunMode { #[clap(name = "--mem", about = "Stores data in memory")] Mem, #[clap(name = "--file", about = "Stores data in local files")] File { #[clap(parse(from_os_str), about = "Path to store data")] path: PathBuf, }, } #[derive(Subcommand)] #[clap(about = "Commands to operate Storage")] enum StorageCommand { #[clap(about = "Run a storage server")] Run { #[clap(about = "Socket address to listen")] addr: String, #[clap(subcommand)] cmd: RunMode, }, } impl StorageCommand { async fn run(&self) -> Result<()> { match self { StorageCommand::Run { addr, cmd } => match cmd { RunMode::File { path } => { let storage = FileStorage::new(&path).await?; let server = StorageServer::new(storage); bootstrap_service!(addr, server); } RunMode::Mem => { let server = StorageServer::new(MemStorage::default()); bootstrap_service!(addr, server); } }, } Ok(
ernelServer::new(journal, storage, kernel); bootstrap_service!(addr, server); } }, } Ok(()) } } #[derive(Parser)] enum SubCommand { #[clap(subcommand)] Storage(StorageCommand), #[clap(subcommand)] Journal(JournalCommand), #[clap(subcommand)] Kernel(KernelCommand), } #[derive(Parser)] #[clap( version = crate_version!(), about = crate_description!(), )] struct Command { #[clap(subcommand)] subcmd: SubCommand, } impl Command { async fn run(&self) -> Result<()> { match &self.subcmd { SubCommand::Storage(cmd) => cmd.run().await?, SubCommand::Journal(cmd) => cmd.run().await?, SubCommand::Kernel(cmd) => cmd.run().await?, } Ok(()) } } #[tokio::main] async fn main() -> Result<()> { let cmd: Command = Command::parse(); cmd.run().await }
()) } } #[derive(Subcommand)] #[clap(about = "Commands to operate Journal")] enum JournalCommand { #[clap(about = "Run a journal server")] Run { #[clap(about = "Socket address to listen")] addr: String, #[clap(subcommand)] cmd: RunMode, #[clap( long, default_value = "67108864", about = "The size of segments in bytes, only taking effects for a file instance" )] segment_size: usize, }, } impl JournalCommand { async fn run(&self) -> Result<()> { match self { JournalCommand::Run { addr, cmd, segment_size, } => match cmd { RunMode::File { path } => { let journal = FileJournal::open(path, *segment_size).await?; let server = JournalServer::new(journal); bootstrap_service!(addr, server); } RunMode::Mem => { let server = JournalServer::new(MemJournal::default()); bootstrap_service!(addr, server); } }, } Ok(()) } } #[derive(Subcommand)] #[clap(about = "Commands to operate Kernel")] enum KernelCommand { #[clap(about = "Run a kernel server")] Run { #[clap(about = "Socket address to listen")] addr: String, #[clap(subcommand)] mode: RunMode, #[clap(long, about = "The address of journal server")] journal: String, #[clap(long, about = "The address of storage server")] storage: String, }, } impl KernelCommand { async fn run(&self) -> Result<()> { match self { KernelCommand::Run { addr, mode: cmd, journal, storage, } => match cmd { RunMode::Mem => { let kernel = MemKernel::open(journal, storage).await?; let server = KernelServer::new(journal, storage, kernel); bootstrap_service!(addr, server); } RunMode::File { path } => { let kernel = FileKernel::open(journal, storage, &path).await?; let server = K
random
[ { "content": "/// The main entrance of engula server.\n\npub fn run(config: Config, executor: Executor, shutdown: Shutdown) -> Result<()> {\n\n executor.block_on(async {\n\n let engines = Engines::open(&config.root_dir, &config.db)?;\n\n\n\n let root_list = if config.init {\n\n vec![...
Rust
rust-runtime/aws-smithy-client/src/lib.rs
floric/smithy-rs
ada03d4ca104f88d16d6732f91ee1d420f1f6d32
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #![warn( missing_debug_implementations, missing_docs, rustdoc::all, rust_2018_idioms )] pub mod bounds; pub mod erase; pub mod retry; #[allow(rustdoc::private_doc_tests)] mod builder; pub use builder::Builder; #[cfg(feature = "test-util")] pub mod dvr; #[cfg(feature = "test-util")] pub mod test_connection; #[cfg(feature = "hyper")] mod hyper_impls; #[cfg(feature = "hyper")] pub mod hyper_ext { pub use crate::hyper_impls::Builder; pub use crate::hyper_impls::HyperAdapter as Adapter; } #[doc(hidden)] pub mod static_tests; pub mod never; pub mod timeout; #[cfg(feature = "hyper")] #[allow(missing_docs)] pub mod conns { #[cfg(feature = "rustls")] pub type Https = hyper_rustls::HttpsConnector<hyper::client::HttpConnector>; #[cfg(feature = "rustls")] lazy_static::lazy_static! { static ref HTTPS_NATIVE_ROOTS: Https = { hyper_rustls::HttpsConnector::with_native_roots() }; } #[cfg(feature = "rustls")] pub fn https() -> Https { HTTPS_NATIVE_ROOTS.clone() } #[cfg(feature = "native-tls")] pub fn native_tls() -> NativeTls { hyper_tls::HttpsConnector::new() } #[cfg(feature = "native-tls")] pub type NativeTls = hyper_tls::HttpsConnector<hyper::client::HttpConnector>; #[cfg(feature = "rustls")] pub type Rustls = crate::hyper_impls::HyperAdapter< hyper_rustls::HttpsConnector<hyper::client::HttpConnector>, >; } use aws_smithy_http::body::SdkBody; use aws_smithy_http::operation::Operation; use aws_smithy_http::response::ParseHttpResponse; pub use aws_smithy_http::result::{SdkError, SdkSuccess}; use aws_smithy_http::retry::ClassifyResponse; use aws_smithy_http_tower::dispatch::DispatchLayer; use aws_smithy_http_tower::parse_response::ParseResponseLayer; use aws_smithy_types::retry::ProvideErrorKind; use std::error::Error; use tower::{Layer, Service, ServiceBuilder, ServiceExt}; #[derive(Debug)] pub struct Client< Connector = erase::DynConnector, Middleware = erase::DynMiddleware<Connector>, RetryPolicy = retry::Standard, > { connector: Connector, middleware: Middleware, retry_policy: RetryPolicy, } impl<C, M> Client<C, M> where M: Default, { pub fn new(connector: C) -> Self { Builder::new() .connector(connector) .middleware(M::default()) .build() } } impl<C, M> Client<C, M> { pub fn set_retry_config(&mut self, config: retry::Config) { self.retry_policy.with_config(config); } pub fn with_retry_config(mut self, config: retry::Config) -> Self { self.set_retry_config(config); self } } fn check_send_sync<T: Send + Sync>(t: T) -> T { t } impl<C, M, R> Client<C, M, R> where C: bounds::SmithyConnector, M: bounds::SmithyMiddleware<C>, R: retry::NewRequestPolicy, { pub async fn call<O, T, E, Retry>(&self, input: Operation<O, Retry>) -> Result<T, SdkError<E>> where O: Send + Sync, Retry: Send + Sync, R::Policy: bounds::SmithyRetryPolicy<O, T, E, Retry>, bounds::Parsed<<M as bounds::SmithyMiddleware<C>>::Service, O, Retry>: Service<Operation<O, Retry>, Response = SdkSuccess<T>, Error = SdkError<E>> + Clone, { self.call_raw(input).await.map(|res| res.parsed) } pub async fn call_raw<O, T, E, Retry>( &self, input: Operation<O, Retry>, ) -> Result<SdkSuccess<T>, SdkError<E>> where O: Send + Sync, Retry: Send + Sync, R::Policy: bounds::SmithyRetryPolicy<O, T, E, Retry>, bounds::Parsed<<M as bounds::SmithyMiddleware<C>>::Service, O, Retry>: Service<Operation<O, Retry>, Response = SdkSuccess<T>, Error = SdkError<E>> + Clone, { let connector = self.connector.clone(); let svc = ServiceBuilder::new() .retry(self.retry_policy.new_request_policy()) .layer(ParseResponseLayer::<O, Retry>::new()) .layer(&self.middleware) .layer(DispatchLayer::new()) .service(connector); check_send_sync(svc).ready().await?.call(input).await } #[doc(hidden)] pub fn check(&self) where R::Policy: tower::retry::Policy< static_tests::ValidTestOperation, SdkSuccess<()>, SdkError<static_tests::TestOperationError>, > + Clone, { let _ = |o: static_tests::ValidTestOperation| { let _ = self.call_raw(o); }; } }
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #![warn( missing_debug_implementations, missing_docs, rustdoc::all, rust_2018_idioms )] pub mod bounds; pub mod erase; pub mod retry; #[allow(rustdoc::private_doc_tests)] mod builder; pub use builder::Builder; #[cfg(feature = "test-util")] pub mod dvr; #[cfg(feature = "test-util")] pub mod test_connection; #[cfg(feature = "hyper")] mod hyper_impls; #[cfg(feature = "hyper")] pub mod hyper_ext { pub use crate::hyper_impls::Builder; pub use crate::hyper_impls::HyperAdapter as Adapter; } #[doc(hidden)] pub mod static_tests; pub mod never; pub mod timeout; #[cfg(feature = "hyper")] #[allow(missing_docs)] pub mod conns { #[cfg(feature = "rustls")] pub type Https = hyper_rustls::HttpsConnector<hyper::client::HttpConnector>; #[cfg(feature = "rustls")] lazy_static::lazy_static! { static ref HTTPS_NATIVE_ROOTS: Https = { hyper_rustls::HttpsConnector::with_native_roots() }; } #[cfg(feature = "rustls")] pub fn https() -> Https { HTTPS_NATIVE_ROOTS.clone() } #[cfg(feature = "native-tls")] pub fn native_tls() -> NativeTls { hyper_tls::HttpsConnector::new() } #[cfg(feature = "native-tls")] pub type NativeTls = hyper_tls::HttpsConnector<hyper::client::HttpConnector>; #[cfg(feature = "rustls")] pub type Rustls = crate::hyper_impls::HyperAdapter< hyper_rustls::HttpsConnector<hyper::client::HttpConnector>, >; } use aws_smithy_http::body::SdkBody; use aws_smithy_http::operation::Operation; use aws_smithy_http::response::ParseHttpResponse; pub use aws_smithy_http::result::{SdkError, SdkSuccess}; use aws_smithy_http::retry::ClassifyResponse; use aws_smithy_http_tower::dispatch::DispatchLayer; use aws_smithy_http_tower::parse_response::ParseResponseLayer; use aws_smithy_types::retry::ProvideErrorKind; use std::error::Error; use tower::{Layer, Service, ServiceBuilder, ServiceExt}; #[derive(Debug)] pub struct Client< Connector = erase::DynConnector, Middleware = erase::DynMiddleware<Connector>, RetryPolicy = retry::Standard, > { connector: Connector, middleware: Middleware, retry_policy: RetryPolicy, } impl<C, M> Client<C, M> where M: Default, { pub fn new(connector: C) -> Self { Builder::new() .connector(connector) .middleware(M::default()) .build() } } impl<C, M> Client<C, M> { pub fn set_retry_config(&mut self, config: retry::Config) { self.retry_policy.with_config(config); } pub fn with_retry_config(mut self, config: retry::Config) -> Self { self.set_retry_config(config); self } } fn check_send_sync<T: Send + Sync>(t: T) -> T { t } impl<C, M, R> Client<C, M, R> where C: bounds::SmithyConnector, M: bounds::SmithyMiddleware<C>, R: retry::NewRequestPolicy, { pub async fn call<O, T, E, Retry>(&self, input: Operation<O, Retry>) -> Result<T, SdkError<E>> where O: Send + Sync, Retry: Send + Sync, R::Policy: bounds::SmithyRetryPolicy<O, T, E, Retry>, bounds::Parsed<<M as bounds::SmithyMiddleware<C>>::Service, O, Retry>: Service<Operation<O, Retry>, Response = SdkSuccess<T>, Error = SdkError<E>> + Clone, { self.call_raw(input).await.map(|res| res.parsed) } pub async fn call_raw<O, T, E, Retry>( &self, input: Operation<O, Retry>, ) -> Result<SdkSuccess<T>, SdkError<E>> where O: Send + Sync, Retry: Send + Sync, R::Policy: bounds::SmithyRetryPolicy<O, T, E, Retry>, bounds::Parsed<<M as bounds::SmithyMiddleware<C>>::Service, O, Retry>: Service<Operation<O, Retry>, Response = SdkSuccess<T>, Error = SdkError<E>> + Clone, { let connector = self.connector.clone(); let svc = ServiceBuilder::new() .retry(self.retry_policy.new_request_policy()) .layer(ParseResponseLayer::<O, Retry>::new()) .layer(&self.middleware) .layer(DispatchLayer::new()) .service(connector); check_send_sync(svc).ready().await?.call(input).await } #[doc(hidden)] pub fn check(&self) where R::Policy: tower::retr
}
y::Policy< static_tests::ValidTestOperation, SdkSuccess<()>, SdkError<static_tests::TestOperationError>, > + Clone, { let _ = |o: static_tests::ValidTestOperation| { let _ = self.call_raw(o); }; }
function_block-function_prefixed
[ { "content": "#[allow(dead_code)]\n\n#[cfg(all(test, feature = \"hyper\"))]\n\nfn sanity_hyper(hc: crate::hyper_impls::HyperAdapter<hyper::client::HttpConnector>) {\n\n Builder::new()\n\n .middleware(tower::layer::util::Identity::new())\n\n .connector(hc)\n\n .build()\n\n .check()...
Rust
tesseract-server/src/app.rs
frabarz/tesseract
4ef7a2cdf8810f0077a35ecbf62fbeb89e383d36
use actix_web::{ http::Method, middleware, App, http::NormalizePath, }; use tesseract_core::{Backend, Schema, CubeHasUniqueLevelsAndProperties}; use crate::db_config::Database; use crate::handlers::{ aggregate_handler, aggregate_default_handler, aggregate_stream_handler, aggregate_stream_default_handler, diagnosis_handler, diagnosis_default_handler, logic_layer_default_handler, logic_layer_handler, logic_layer_non_unique_levels_handler, logic_layer_non_unique_levels_default_handler, logic_layer_members_handler, logic_layer_members_default_handler, flush_handler, index_handler, metadata_handler, metadata_all_handler, members_handler, members_default_handler, logic_layer_relations_handler, logic_layer_relations_default_handler, logic_layer_relations_non_unique_levels_default_handler, logic_layer_relations_non_unique_levels_handler }; use crate::logic_layer::{Cache, LogicLayerConfig}; use std::sync::{Arc, RwLock}; use url::Url; use r2d2_redis::{r2d2, RedisConnectionManager}; #[derive(Debug, Clone)] pub enum SchemaSource { LocalSchema { filepath: String }, #[allow(dead_code)] RemoteSchema { endpoint: String }, } #[derive(Debug, Clone)] pub struct EnvVars { pub database_url: String, pub geoservice_url: Option<Url>, pub schema_source: SchemaSource, pub jwt_secret: Option<String>, pub flush_secret: Option<String>, } pub struct AppState { pub debug: bool, pub backend: Box<dyn Backend + Sync + Send>, pub redis_pool: Option<r2d2::Pool<RedisConnectionManager>>, pub db_type: Database, pub env_vars: EnvVars, pub schema: Arc<RwLock<Schema>>, pub cache: Arc<RwLock<Cache>>, pub logic_layer_config: Option<Arc<RwLock<LogicLayerConfig>>>, pub has_unique_levels_properties: CubeHasUniqueLevelsAndProperties, } pub fn create_app( debug: bool, backend: Box<dyn Backend + Sync + Send>, redis_pool: Option<r2d2::Pool<RedisConnectionManager>>, db_type: Database, env_vars: EnvVars, schema: Arc<RwLock<Schema>>, cache: Arc<RwLock<Cache>>, logic_layer_config: Option<Arc<RwLock<LogicLayerConfig>>>, streaming_response: bool, has_unique_levels_properties: CubeHasUniqueLevelsAndProperties, ) -> App<AppState> { let app = App::with_state( AppState { debug, backend, redis_pool, db_type, env_vars, schema, cache, logic_layer_config, has_unique_levels_properties: has_unique_levels_properties.clone(), }) .middleware(middleware::Logger::default()) .middleware(middleware::DefaultHeaders::new().header("Vary", "Accept-Encoding")) .resource("/", |r| { r.method(Method::GET).with(index_handler) }) .resource("/cubes", |r| { r.method(Method::GET).with(metadata_all_handler) }) .resource("/cubes/{cube}", |r| { r.method(Method::GET).with(metadata_handler) }) .resource("/cubes/{cube}/members", |r| { r.method(Method::GET).with(members_default_handler) }) .resource("/cubes/{cube}/members.{format}", |r| { r.method(Method::GET).with(members_handler) }) .resource("/diagnosis", |r| { r.method(Method::GET).with(diagnosis_default_handler) }) .resource("/diagnosis.{format}", |r| { r.method(Method::GET).with(diagnosis_handler) }) .resource("/flush", |r| { r.method(Method::POST).with(flush_handler) }) .default_resource(|r| r.h(NormalizePath::default())); let app = if streaming_response { app .resource("/cubes/{cube}/aggregate", |r| { r.method(Method::GET).with(aggregate_stream_default_handler) }) .resource("/cubes/{cube}/aggregate.{format}", |r| { r.method(Method::GET).with(aggregate_stream_handler) }) } else { app .resource("/cubes/{cube}/aggregate", |r| { r.method(Method::GET).with(aggregate_default_handler) }) .resource("/cubes/{cube}/aggregate.{format}", |r| { r.method(Method::GET).with(aggregate_handler) }) }; match has_unique_levels_properties { CubeHasUniqueLevelsAndProperties::True => { app .resource("/data", |r| { r.method(Method::GET).with(logic_layer_default_handler) }) .resource("/data.{format}", |r| { r.method(Method::GET).with(logic_layer_handler) }) .resource("/members", |r| { r.method(Method::GET).with(logic_layer_members_default_handler) }) .resource("/members.{format}", |r| { r.method(Method::GET).with(logic_layer_members_handler) }) .resource("/relations", |r| { r.method(Method::GET).with(logic_layer_relations_default_handler) }) .resource("/relations.{foramt}", |r| { r.method(Method::GET).with(logic_layer_relations_handler) }) }, CubeHasUniqueLevelsAndProperties::False { .. } => { app .resource("/data", |r| { r.method(Method::GET).with(logic_layer_non_unique_levels_default_handler) }) .resource("/data.{format}", |r| { r.method(Method::GET).with(logic_layer_non_unique_levels_handler) }) .resource("/members", |r| { r.method(Method::GET).with(logic_layer_non_unique_levels_default_handler) }) .resource("/members.{format}", |r| { r.method(Method::GET).with(logic_layer_non_unique_levels_handler) }) .resource("/relations", |r| { r.method(Method::GET).with(logic_layer_relations_non_unique_levels_default_handler) }) .resource("/relations.{foramt}", |r| { r.method(Method::GET).with(logic_layer_relations_non_unique_levels_handler) }) }, } }
use actix_web::{ http::Method, middleware, App, http::NormalizePath, }; use tesseract_core::{Backend, Schema, CubeHasUniqueLevelsAndProperties}; use crate::db_config::Database; use crate::handlers::{ aggregate_handler, aggregate_default_handler, aggregate_stream_handler, aggregate_stream_default_handler, diagnosis_handler, diagnosis_default_handler, logic_layer_default_handler, logic_layer_handler, logic_layer_non_unique_levels_handler, logic_layer_non_unique_levels_default_handler, logic_layer_members_handler, logic_layer_members_default_handler, flush_handler, index_handler, metadata_handler, metadata_all_handler, members_handler, members_default_handler, logic_layer_relations_handler, logic_layer_relations_default_handler, logic_layer_relations_non_unique_levels_default_handler, logic_layer_relations_non_unique_levels_handler }; use crate::logic_layer::{Cache, LogicLayerConfig}; use std::sync::{Arc, RwLock}; use url::Url; use r2d2_redis::{r2d2, RedisConnectionManager}; #[derive(Debug, Clone)] pub enum SchemaSource { LocalSchema { filepath: String }, #[allow(dead_code)] RemoteSchema { endpoint: String }, } #[derive(Debug, Clone)] pub struct EnvVars { pub database_url: String, pub geoservice_url: Option<Url>, pub schema_source: SchemaSource, pub jwt_secret: Option<String>, pub flush_secret: Option<String>, } pub struct AppState { pub debug: bool, pub backend: Box<dyn Backend + Sync + Send>, pub redis_pool: Option<r2d2::Pool<RedisConnectionManager>>, pub db_type: Database, pub env_vars: EnvVars, pub schema: Arc<RwLock<Schema>>, pub cache: Arc<RwLock<Cache>>, pub logic_layer_config: Option<Arc<RwLock<LogicLayerConfig>>>, pub has_unique_levels_properties: CubeHasUniqueLevelsAndProperties, } pub fn create_app( debug: bool, backend: Box<dyn Backend + Sync + Send>, redis_pool: Option<r2d2::Pool<RedisConnectionManager>>, db_type: Database, env_vars: EnvVars, schema: Arc<RwLock<Schema>>, cache: Arc<RwLock<Cache>>, logic_layer_config: Option<Arc<RwLock<LogicLayerConfig>>>, streaming_response: bool, has_unique_levels_properties: CubeHasUniqueLevelsAndProperties, ) -> App<AppState> { let app = App::with_state( AppState { debug, backend, redis_pool, db_type, env_vars, schema, cache, logic_layer_config, has_unique_levels_properties: has_unique_levels_properties.clone(), }) .middleware(middleware::Logger::default()) .middleware(middleware::DefaultHeaders::new().header("Vary", "Accept-Encoding")) .resource("/", |r| { r.method(Method::GET).with(index_handler) }) .resource("/cubes", |r| { r.method(Method::GET).with(metadata_all_handler) }) .resource("/cubes/{cube}", |r| { r.method(Method::GET).with(metadata_handler) }) .resource("/cubes/{cube}/members", |r| { r.method(Method::GET).with(members_default_handler) }) .resource("/cubes/{cube}/members.{format}", |r| { r.method(Method::GET).with(members_handler) }) .resource("/diagnosis", |r| { r.method(Method::GET).with(diagnosis_default_handler) }) .resource("/diagnosis.{format}", |r| { r.method(Method::GET).with(diagnosis_handler) }) .resource("/flush", |r| { r.method(Method::POST).with(flush_handler) }) .default_resource(|r| r.h(NormalizePath::default())); let app =
; match has_unique_levels_properties { CubeHasUniqueLevelsAndProperties::True => { app .resource("/data", |r| { r.method(Method::GET).with(logic_layer_default_handler) }) .resource("/data.{format}", |r| { r.method(Method::GET).with(logic_layer_handler) }) .resource("/members", |r| { r.method(Method::GET).with(logic_layer_members_default_handler) }) .resource("/members.{format}", |r| { r.method(Method::GET).with(logic_layer_members_handler) }) .resource("/relations", |r| { r.method(Method::GET).with(logic_layer_relations_default_handler) }) .resource("/relations.{foramt}", |r| { r.method(Method::GET).with(logic_layer_relations_handler) }) }, CubeHasUniqueLevelsAndProperties::False { .. } => { app .resource("/data", |r| { r.method(Method::GET).with(logic_layer_non_unique_levels_default_handler) }) .resource("/data.{format}", |r| { r.method(Method::GET).with(logic_layer_non_unique_levels_handler) }) .resource("/members", |r| { r.method(Method::GET).with(logic_layer_non_unique_levels_default_handler) }) .resource("/members.{format}", |r| { r.method(Method::GET).with(logic_layer_non_unique_levels_handler) }) .resource("/relations", |r| { r.method(Method::GET).with(logic_layer_relations_non_unique_levels_default_handler) }) .resource("/relations.{foramt}", |r| { r.method(Method::GET).with(logic_layer_relations_non_unique_levels_handler) }) }, } }
if streaming_response { app .resource("/cubes/{cube}/aggregate", |r| { r.method(Method::GET).with(aggregate_stream_default_handler) }) .resource("/cubes/{cube}/aggregate.{format}", |r| { r.method(Method::GET).with(aggregate_stream_handler) }) } else { app .resource("/cubes/{cube}/aggregate", |r| { r.method(Method::GET).with(aggregate_default_handler) }) .resource("/cubes/{cube}/aggregate.{format}", |r| { r.method(Method::GET).with(aggregate_handler) }) }
if_condition
[]
Rust
kernel-rs/src/bio.rs
anemoneflower/rv6-1
9dc037339e9d0991c2d8dc4408517fb6d0dcb270
use crate::{ arena::{Arena, ArenaObject, MruArena, MruEntry, Rc}, param::{BSIZE, NBUF}, proc::WaitChannel, sleeplock::Sleeplock, spinlock::Spinlock, }; use core::mem; use core::ops::{Deref, DerefMut}; pub struct BufEntry { dev: u32, pub blockno: u32, pub vdisk_request_waitchannel: WaitChannel, pub inner: Sleeplock<BufInner>, } impl BufEntry { pub const fn zero() -> Self { Self { dev: 0, blockno: 0, vdisk_request_waitchannel: WaitChannel::new(), inner: Sleeplock::new("buffer", BufInner::zero()), } } } impl ArenaObject for BufEntry { fn finalize<'s, A: Arena>(&'s mut self, _guard: &'s mut A::Guard<'_>) { } } pub struct BufInner { pub valid: bool, pub disk: bool, pub data: [u8; BSIZE], } impl BufInner { const fn zero() -> Self { Self { valid: false, disk: false, data: [0; BSIZE], } } } pub type Bcache = Spinlock<MruArena<BufEntry, NBUF>>; pub type BufUnlocked<'s> = Rc<Bcache, &'s Bcache>; pub struct Buf<'s> { inner: BufUnlocked<'s>, } impl<'s> Deref for Buf<'s> { type Target = BufUnlocked<'s>; fn deref(&self) -> &Self::Target { &self.inner } } impl DerefMut for Buf<'_> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner } } impl<'s> Buf<'s> { pub fn deref_inner(&self) -> &BufInner { unsafe { self.inner.inner.get_mut_unchecked() } } pub fn deref_inner_mut(&mut self) -> &mut BufInner { unsafe { self.inner.inner.get_mut_unchecked() } } pub fn unlock(self) -> BufUnlocked<'s> { unsafe { self.inner.inner.unlock(); mem::transmute(self) } } } impl Drop for Buf<'_> { fn drop(&mut self) { unsafe { self.inner.inner.unlock(); } } } impl Bcache { pub const fn zero() -> Self { Spinlock::new( "BCACHE", MruArena::new(array![_ => MruEntry::new(BufEntry::zero()); NBUF]), ) } pub fn get_buf(&self, dev: u32, blockno: u32) -> BufUnlocked<'_> { let inner = self .find_or_alloc( |buf| buf.dev == dev && buf.blockno == blockno, |buf| { buf.dev = dev; buf.blockno = blockno; buf.inner.get_mut().valid = false; }, ) .expect("[BufGuard::new] no buffers"); unsafe { Rc::from_unchecked(self, inner) } } pub fn buf_unforget(&self, dev: u32, blockno: u32) -> Option<BufUnlocked<'_>> { let inner = self.unforget(|buf| buf.dev == dev && buf.blockno == blockno)?; Some(unsafe { Rc::from_unchecked(self, inner) }) } } impl<'s> BufUnlocked<'s> { pub fn lock(self) -> Buf<'s> { mem::forget(self.inner.lock()); Buf { inner: self } } pub fn deref_inner(&self) -> &BufInner { unsafe { self.inner.get_mut_unchecked() } } pub fn deref_mut_inner(&mut self) -> &mut BufInner { unsafe { self.inner.get_mut_unchecked() } } }
use crate::{ arena::{Arena, ArenaObject, MruArena, MruEntry, Rc}, param::{BSIZE, NBUF}, proc::WaitChannel, sleeplock::Sleeplock, spinlock::Spinlock, }; use core::mem; use core::ops::{Deref, DerefMut}; pub struct BufEntry { dev: u32, pub blockno: u32, pub vdisk_request_waitchannel: WaitChannel, pub inner: Sleeplock<BufInner>, } impl BufEntry { pub const fn zero() -> Self { Self { dev: 0, blockno: 0, vdisk_request_waitchannel: WaitChannel::new(), inner: Sleeplock::new("buffer", BufInner::zero()), } } } impl ArenaObject for BufEntry { fn finalize<'s, A: Arena>(&'s mut self, _guard: &'s mut A::Guard<'_>) { } } pub struct BufInner { pub valid: bool, pub disk: bool, pub data: [u8; BSIZE], } impl BufInner { const fn zero() -> Self { Self { valid: false, disk: false, data: [0; BSIZE], } } } pub type Bcache = Spinlock<MruArena<BufEntry, NBUF>>; pub type BufUnlocked<'s> = Rc<Bcache, &'s Bcache>; pub struct Buf<'s> { inner: BufUnlocked<'s>, } impl<'s> Deref for Buf<'s> { type Target = BufUnlocked<'s>; fn deref(&self) -> &Self::Target { &self.inner } } impl DerefMut for Buf<'_> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner } } impl<'s> Buf<'s> { pub fn deref_inner(&self) -> &BufInner { unsafe { self.inner.inner.get_mut_unchecked() } } pub fn deref_inner_mut(&mut self) -> &mut BufInner { unsafe { self.inner.inner.get_mut_unchecked() } } pub fn unlock(self) -> BufUnlocked<'s> { unsafe { self.inner.inner.unlock(); mem::transmute(self) } } } impl Drop for Buf<'_> { fn drop(&mut self) { unsafe { self.inner.inner.unlock(); } } } impl Bcache { pub const fn zero() -> Self { Spinlock::new( "BCACHE", MruArena::new(array![_ => MruEntry::new(BufEntry::zero()); NBUF]), ) }
pub fn buf_unforget(&self, dev: u32, blockno: u32) -> Option<BufUnlocked<'_>> { let inner = self.unforget(|buf| buf.dev == dev && buf.blockno == blockno)?; Some(unsafe { Rc::from_unchecked(self, inner) }) } } impl<'s> BufUnlocked<'s> { pub fn lock(self) -> Buf<'s> { mem::forget(self.inner.lock()); Buf { inner: self } } pub fn deref_inner(&self) -> &BufInner { unsafe { self.inner.get_mut_unchecked() } } pub fn deref_mut_inner(&mut self) -> &mut BufInner { unsafe { self.inner.get_mut_unchecked() } } }
pub fn get_buf(&self, dev: u32, blockno: u32) -> BufUnlocked<'_> { let inner = self .find_or_alloc( |buf| buf.dev == dev && buf.blockno == blockno, |buf| { buf.dev = dev; buf.blockno = blockno; buf.inner.get_mut().valid = false; }, ) .expect("[BufGuard::new] no buffers"); unsafe { Rc::from_unchecked(self, inner) } }
function_block-full_function
[ { "content": "pub trait ArenaObject {\n\n fn finalize<'s, A: Arena>(&'s mut self, guard: &'s mut A::Guard<'_>);\n\n}\n\n\n\npub struct ArrayEntry<T> {\n\n refcnt: usize,\n\n data: T,\n\n}\n\n\n\n/// A homogeneous memory allocator equipped with reference counts.\n\npub struct ArrayArena<T, const CAPACIT...
Rust
src/flash/efuse.rs
jeandudey/cc13x2-rs
215918099301ec75e9dfad531f5cf46e13077a39
#[doc = "Reader of register EFUSE"] pub type R = crate::R<u32, super::EFUSE>; #[doc = "Writer for register EFUSE"] pub type W = crate::W<u32, super::EFUSE>; #[doc = "Register EFUSE `reset()`'s with value 0"] impl crate::ResetValue for super::EFUSE { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `RESERVED29`"] pub type RESERVED29_R = crate::R<u8, u8>; #[doc = "Write proxy for field `RESERVED29`"] pub struct RESERVED29_W<'a> { w: &'a mut W, } impl<'a> RESERVED29_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x07 << 29)) | (((value as u32) & 0x07) << 29); self.w } } #[doc = "Reader of field `INSTRUCTION`"] pub type INSTRUCTION_R = crate::R<u8, u8>; #[doc = "Write proxy for field `INSTRUCTION`"] pub struct INSTRUCTION_W<'a> { w: &'a mut W, } impl<'a> INSTRUCTION_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x1f << 24)) | (((value as u32) & 0x1f) << 24); self.w } } #[doc = "Reader of field `RESERVED16`"] pub type RESERVED16_R = crate::R<u8, u8>; #[doc = "Write proxy for field `RESERVED16`"] pub struct RESERVED16_W<'a> { w: &'a mut W, } impl<'a> RESERVED16_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0xff << 16)) | (((value as u32) & 0xff) << 16); self.w } } #[doc = "Reader of field `DUMPWORD`"] pub type DUMPWORD_R = crate::R<u16, u16>; #[doc = "Write proxy for field `DUMPWORD`"] pub struct DUMPWORD_W<'a> { w: &'a mut W, } impl<'a> DUMPWORD_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !0xffff) | ((value as u32) & 0xffff); self.w } } impl R { #[doc = "Bits 29:31 - 31:29\\] Internal. Only to be used through TI provided API."] #[inline(always)] pub fn reserved29(&self) -> RESERVED29_R { RESERVED29_R::new(((self.bits >> 29) & 0x07) as u8) } #[doc = "Bits 24:28 - 28:24\\] Internal. Only to be used through TI provided API."] #[inline(always)] pub fn instruction(&self) -> INSTRUCTION_R { INSTRUCTION_R::new(((self.bits >> 24) & 0x1f) as u8) } #[doc = "Bits 16:23 - 23:16\\] Internal. Only to be used through TI provided API."] #[inline(always)] pub fn reserved16(&self) -> RESERVED16_R { RESERVED16_R::new(((self.bits >> 16) & 0xff) as u8) } #[doc = "Bits 0:15 - 15:0\\] Internal. Only to be used through TI provided API."] #[inline(always)] pub fn dumpword(&self) -> DUMPWORD_R { DUMPWORD_R::new((self.bits & 0xffff) as u16) } } impl W { #[doc = "Bits 29:31 - 31:29\\] Internal. Only to be used through TI provided API."] #[inline(always)] pub fn reserved29(&mut self) -> RESERVED29_W { RESERVED29_W { w: self } } #[doc = "Bits 24:28 - 28:24\\] Internal. Only to be used through TI provided API."] #[inline(always)] pub fn instruction(&mut self) -> INSTRUCTION_W { INSTRUCTION_W { w: self } } #[doc = "Bits 16:23 - 23:16\\] Internal. Only to be used through TI provided API."] #[inline(always)] pub fn reserved16(&mut self) -> RESERVED16_W { RESERVED16_W { w: self } } #[doc = "Bits 0:15 - 15:0\\] Internal. Only to be used through TI provided API."] #[inline(always)] pub fn dumpword(&mut self) -> DUMPWORD_W { DUMPWORD_W { w: self } } }
#[doc = "Reader of register EFUSE"] pub type R = crate::R<u32, super::EFUSE>; #[doc = "Writer for register EFUSE"] pub type W = crate::W<u32, super::EFUSE>; #[doc = "Register EFUSE `reset()`'s with value 0"] impl crate::ResetValue for super::EFUSE { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `RESERVED29`"]
mut W, } impl<'a> INSTRUCTION_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x1f << 24)) | (((value as u32) & 0x1f) << 24); self.w } } #[doc = "Reader of field `RESERVED16`"] pub type RESERVED16_R = crate::R<u8, u8>; #[doc = "Write proxy for field `RESERVED16`"] pub struct RESERVED16_W<'a> { w: &'a mut W, } impl<'a> RESERVED16_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0xff << 16)) | (((value as u32) & 0xff) << 16); self.w } } #[doc = "Reader of field `DUMPWORD`"] pub type DUMPWORD_R = crate::R<u16, u16>; #[doc = "Write proxy for field `DUMPWORD`"] pub struct DUMPWORD_W<'a> { w: &'a mut W, } impl<'a> DUMPWORD_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !0xffff) | ((value as u32) & 0xffff); self.w } } impl R { #[doc = "Bits 29:31 - 31:29\\] Internal. Only to be used through TI provided API."] #[inline(always)] pub fn reserved29(&self) -> RESERVED29_R { RESERVED29_R::new(((self.bits >> 29) & 0x07) as u8) } #[doc = "Bits 24:28 - 28:24\\] Internal. Only to be used through TI provided API."] #[inline(always)] pub fn instruction(&self) -> INSTRUCTION_R { INSTRUCTION_R::new(((self.bits >> 24) & 0x1f) as u8) } #[doc = "Bits 16:23 - 23:16\\] Internal. Only to be used through TI provided API."] #[inline(always)] pub fn reserved16(&self) -> RESERVED16_R { RESERVED16_R::new(((self.bits >> 16) & 0xff) as u8) } #[doc = "Bits 0:15 - 15:0\\] Internal. Only to be used through TI provided API."] #[inline(always)] pub fn dumpword(&self) -> DUMPWORD_R { DUMPWORD_R::new((self.bits & 0xffff) as u16) } } impl W { #[doc = "Bits 29:31 - 31:29\\] Internal. Only to be used through TI provided API."] #[inline(always)] pub fn reserved29(&mut self) -> RESERVED29_W { RESERVED29_W { w: self } } #[doc = "Bits 24:28 - 28:24\\] Internal. Only to be used through TI provided API."] #[inline(always)] pub fn instruction(&mut self) -> INSTRUCTION_W { INSTRUCTION_W { w: self } } #[doc = "Bits 16:23 - 23:16\\] Internal. Only to be used through TI provided API."] #[inline(always)] pub fn reserved16(&mut self) -> RESERVED16_W { RESERVED16_W { w: self } } #[doc = "Bits 0:15 - 15:0\\] Internal. Only to be used through TI provided API."] #[inline(always)] pub fn dumpword(&mut self) -> DUMPWORD_W { DUMPWORD_W { w: self } } }
pub type RESERVED29_R = crate::R<u8, u8>; #[doc = "Write proxy for field `RESERVED29`"] pub struct RESERVED29_W<'a> { w: &'a mut W, } impl<'a> RESERVED29_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x07 << 29)) | (((value as u32) & 0x07) << 29); self.w } } #[doc = "Reader of field `INSTRUCTION`"] pub type INSTRUCTION_R = crate::R<u8, u8>; #[doc = "Write proxy for field `INSTRUCTION`"] pub struct INSTRUCTION_W<'a> { w: &'a
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/biunify/mod.rs
andrewhickman/mlsub-rs
f6011bf12ba4b834315a9dfdfcd942747f796566
#[cfg(test)] mod reference; #[cfg(test)] mod tests; use std::convert::Infallible; use std::fmt::{self, Debug}; use std::iter::once; use crate::auto::{Automaton, StateId}; use crate::{Constructor, Label, Polarity}; pub type Result<C> = std::result::Result<(), Error<C>>; #[derive(Debug)] pub struct Error<C: Constructor> { pub stack: Vec<(C::Label, C, C)>, pub constraint: (C, C), } pub(crate) enum CacheEntry<C: Constructor> { Root, RequiredBy { label: C::Label, pos: (StateId, C), neg: (StateId, C), }, } impl<C: Constructor> Automaton<C> { pub fn biunify(&mut self, qp: StateId, qn: StateId) -> Result<C> { self.biunify_all(once((qp, qn))) } pub fn biunify_all<I>(&mut self, constraints: I) -> Result<C> where I: IntoIterator<Item = (StateId, StateId)>, { let mut stack = Vec::with_capacity(20); stack.extend(constraints.into_iter().filter(|&constraint| { self.biunify_cache .insert(constraint, CacheEntry::Root) .is_none() })); while let Some(constraint) = stack.pop() { self.biunify_impl(&mut stack, constraint)?; } Ok(()) } fn biunify_impl( &mut self, stack: &mut Vec<(StateId, StateId)>, (qp, qn): (StateId, StateId), ) -> Result<C> { #[cfg(debug_assertions)] debug_assert_eq!(self[qp].pol, Polarity::Pos); #[cfg(debug_assertions)] debug_assert_eq!(self[qn].pol, Polarity::Neg); debug_assert!(self.biunify_cache.contains_key(&(qp, qn))); for (cp, cn) in product(self[qp].cons.iter(), self[qn].cons.iter()) { if !(cp <= cn) { return Err(self.make_error((qp, cp.clone()), (qn, cn.clone()))); } } for to in self[qn].flow.iter() { self.merge(Polarity::Pos, to, qp); } for from in self[qp].flow.iter() { self.merge(Polarity::Neg, from, qn); } let states = &self.states; let biunify_cache = &mut self.biunify_cache; let cps = &states[qp.as_u32() as usize].cons; let cns = &states[qn.as_u32() as usize].cons; for (cp, cn) in cps.intersection(cns) { cp.visit_params_intersection::<_, Infallible>(&cn, |label, l, r| { let (ps, ns) = label.polarity().flip(l, r); stack.extend(product(ps, ns).filter(|&constraint| { biunify_cache .insert( constraint, CacheEntry::RequiredBy { label: label.clone(), pos: (qp, cp.clone()), neg: (qn, cn.clone()), }, ) .is_none() })); Ok(()) }) .unwrap(); } Ok(()) } fn make_error(&self, pos: (StateId, C), neg: (StateId, C)) -> Error<C> { let mut stack = Vec::new(); let mut key = (pos.0, neg.0); while let CacheEntry::RequiredBy { label, pos, neg } = &self.biunify_cache[&key] { stack.push((label.clone(), pos.1.clone(), neg.1.clone())); key = (pos.0, neg.0); } Error { stack, constraint: (pos.1, neg.1), } } } fn product<I, J>(lhs: I, rhs: J) -> impl Iterator<Item = (I::Item, J::Item)> where I: IntoIterator, I::Item: Clone + Copy, J: IntoIterator, J: Clone, { lhs.into_iter() .flat_map(move |l| rhs.clone().into_iter().map(move |r| (l.clone(), r))) } impl<C> Debug for CacheEntry<C> where C: Constructor + Debug, C::Label: Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { CacheEntry::Root => f.debug_struct("Root").finish(), CacheEntry::RequiredBy { label, pos, neg } => f .debug_struct("RequiredBy") .field("label", label) .field("pos", pos) .field("neg", neg) .finish(), } } }
#[cfg(test)] mod reference; #[cfg(test)] mod tests; use std::convert::Infallible; use std::fmt::{self, Debug}; use std::iter::once; use crate::auto::{Automaton, StateId}; use crate::{Constructor, Label, Polarity}; pub type Result<C> = std::result::Result<(), Error<C>>; #[derive(Debug)] pub struct Error<C: Constructor> { pub stack: Vec<(C::Label, C, C)>, pub constraint: (C, C), } pub(crate) enum CacheEntry<C: Constructor> { Root, RequiredBy { label: C::Label, pos: (StateId, C), neg: (StateId, C), }, } impl<C: Constructor> Automaton<C> { pub fn biunify(&mut self, qp: StateId, qn: StateId) -> Result<C> { self.biunify_all(once((qp, qn))) } pub fn biunify_all<I>(&mut self, constraints: I) -> Result<C> where I: IntoIterator<Item = (StateId, StateId)>, { let mut stack = Vec::with_capacity(20); stack.extend(constraints.into_iter().filter(|&constraint| { self.biunify_cache .insert(constraint, CacheEntry::Root) .is_none() })); while let Some(constraint) = stack.pop() { self.biunify_impl(&mut stack, constraint)?; } Ok(()) } fn biunify_impl( &mut self, stack: &mut Vec<(StateId, StateId)>, (qp, qn): (StateId, StateId), ) -> Result<C> { #[cfg(debug_assertions)] debug_assert_eq!(self[qp].pol, Polarity::Pos); #[cfg(debug_assertions)] debug_assert_eq!(self[qn].pol, Polarity::Neg); debug_assert!(self.biunify_cache.contains_key(&(qp, qn))); for (cp, cn) in product(self[qp].cons.iter(), self[qn].cons.iter()) { if !(cp <= cn) { return Err(self.make_error((qp, cp.clone()), (qn, cn.clone()))); } } for to in self[qn].flow.iter() { self.merge(Polarity::Pos, to, qp); } for from in self[qp].flow.iter() { self.merge(Polarity::Neg, from, qn); } let states = &self.states; let biunify_cache = &mut self.biunify_cache; let cps = &states[qp.as_u32() as usize].cons; let cns = &states[qn.as_u32() as usize].cons; for (cp, cn) in cps.intersection(cns) { cp.visit_params_intersection::<_, Infallible>(&cn, |label, l, r| { let (ps, ns) = label.polarity().flip(l, r); stack.extend(product(ps, ns).filter(|&constraint| { biunify_cache .insert( constraint, CacheEntry::RequiredBy { label: label.clone(), pos: (qp, cp.clone()), neg: (qn, cn.clone()), }, ) .is_none() })); Ok(()) }) .unwrap(); } Ok(())
m = (I::Item, J::Item)> where I: IntoIterator, I::Item: Clone + Copy, J: IntoIterator, J: Clone, { lhs.into_iter() .flat_map(move |l| rhs.clone().into_iter().map(move |r| (l.clone(), r))) } impl<C> Debug for CacheEntry<C> where C: Constructor + Debug, C::Label: Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { CacheEntry::Root => f.debug_struct("Root").finish(), CacheEntry::RequiredBy { label, pos, neg } => f .debug_struct("RequiredBy") .field("label", label) .field("pos", pos) .field("neg", neg) .finish(), } } }
} fn make_error(&self, pos: (StateId, C), neg: (StateId, C)) -> Error<C> { let mut stack = Vec::new(); let mut key = (pos.0, neg.0); while let CacheEntry::RequiredBy { label, pos, neg } = &self.biunify_cache[&key] { stack.push((label.clone(), pos.1.clone(), neg.1.clone())); key = (pos.0, neg.0); } Error { stack, constraint: (pos.1, neg.1), } } } fn product<I, J>(lhs: I, rhs: J) -> impl Iterator<Ite
random
[ { "content": "pub fn arb_auto_ty(pol: Polarity) -> BoxedStrategy<(Automaton<Constructor>, StateId)> {\n\n arb_polar_ty(pol)\n\n .prop_map(move |ty| {\n\n let mut auto = Automaton::new();\n\n let mut builder = auto.builder();\n\n let id = builder.build_polar(pol, &ty);\...
Rust
kaylee/src/vm.rs
electricjones/kaylee
6cdc7e67ae8a3d9a989d8d18def496c9ceecab40
use crate::instructions::{decode_next_instruction, Instruction}; use crate::program::{Program, ProgramIndex}; pub type RegisterId = usize; pub type RegisterValue = i32; pub type Byte = u8; pub type HalfWord = u16; pub type Word = u32; pub type DoubleWord = u32; pub enum ExecutionResult { Halted, NoAction, Value(RegisterValue), Jumped(ProgramIndex), Equality(bool), } pub enum ExecutionError { Unknown(String), } pub struct Kaylee { registers: [RegisterValue; Kaylee::REGISTER_COUNT], program_counter: RegisterId, remainder: u32, halted: bool, } impl Kaylee { pub const REGISTER_COUNT: usize = 32; pub fn new() -> Self { Kaylee { registers: [0; Kaylee::REGISTER_COUNT], remainder: 0, program_counter: 0, halted: false, } } pub fn run(&mut self, program: Program) { while let Some(result) = decode_next_instruction(&program, &mut self.program_counter) { match result { Ok(instruction) => { self.execute_instruction(instruction) } Err(_error) => { panic!("Error decoding instruction") } } if self.halted { break; } } } pub fn run_next(&mut self, program: &Program) { match decode_next_instruction(program, &mut self.program_counter) { Some(Ok(instruction)) => self.execute_instruction(instruction), None => println!("Execution Finished"), Some(Err(_error)) => panic!("received an error"), }; } fn execute_instruction(&mut self, instruction: Box<dyn Instruction>) { instruction.execute(self).unwrap(); } pub(crate) fn register(&self, register: RegisterId) -> Result<RegisterValue, ()> { if register > Kaylee::REGISTER_COUNT - 1 { return Err(()); } Ok(*&self.registers[register].clone()) } pub(crate) fn all_registers(&self) -> [RegisterValue; Kaylee::REGISTER_COUNT] { *&self.registers.clone() } pub(crate) fn set_register(&mut self, register: RegisterId, value: RegisterValue) -> Result<(), ()> { if register > Kaylee::REGISTER_COUNT - 1 { return Err(()); } self.registers[register] = value; Ok(()) } pub(crate) fn halt(&mut self) { self.halted = true; } pub(crate) fn remainder(&self) -> u32 { self.remainder } pub(crate) fn set_remainder(&mut self, remainder: u32) { self.remainder = remainder } pub(crate) fn program_counter(&self) -> ProgramIndex { self.program_counter } pub(crate) fn set_program_counter(&mut self, index: ProgramIndex) { self.program_counter = index } } #[cfg(test)] mod tests { }
use crate::instructions::{decode_next_instruction, Instruction}; use crate::program::{Program, ProgramIndex}; pub type RegisterId = usize; pub type RegisterValue = i32; pub type Byte = u8; pub type HalfWord = u16; pub type Word = u32; pub type DoubleWord = u32; pub enum ExecutionResult { Halted, NoAction, Value(RegisterValue), Jumped(ProgramIndex), Equality(bool), } pub enum ExecutionError { Unknown(String), } pub struct Kaylee { registers: [RegisterValue; Kaylee::REGISTER_COUNT], program_counter: RegisterId, remainder: u32, halted: bool, } impl Kaylee { pub const REGISTER_COUNT: usize = 32; pub fn new() -> Self { Kaylee { registers: [0; Kaylee::REGISTER_COUNT], remainder: 0, program_counter: 0, halted: false, } } pub fn run(&mut self, program: Program) { while let Some(result) = decode_next_instruction(&program, &mut self.program_counter) { match result { Ok(instruction) => { self.execute_instruction(instruction) } Err(_error) => { panic!("Error decoding instruction") } } if self.halted { break; } } } pub fn run_next(&mut self, program: &Program) { match decode_next_instruction(program, &mut self.program_counter) { Some(Ok(instruction)) => self.execute_instruction(instruction), None => println!("Execution Finished"), Some(Err(_error)) => panic!("received an error"), }; } fn execute_instruction(&mut self, instruction: Box<dyn Instruction>) { instruction.execute(self).unwrap(); } pub(crate) fn register(&self, register: RegisterId) -> Result<RegisterValue, ()> { if register > Kaylee::REGISTER_COUNT - 1 { return Err(()); }
x { self.program_counter } pub(crate) fn set_program_counter(&mut self, index: ProgramIndex) { self.program_counter = index } } #[cfg(test)] mod tests { }
Ok(*&self.registers[register].clone()) } pub(crate) fn all_registers(&self) -> [RegisterValue; Kaylee::REGISTER_COUNT] { *&self.registers.clone() } pub(crate) fn set_register(&mut self, register: RegisterId, value: RegisterValue) -> Result<(), ()> { if register > Kaylee::REGISTER_COUNT - 1 { return Err(()); } self.registers[register] = value; Ok(()) } pub(crate) fn halt(&mut self) { self.halted = true; } pub(crate) fn remainder(&self) -> u32 { self.remainder } pub(crate) fn set_remainder(&mut self, remainder: u32) { self.remainder = remainder } pub(crate) fn program_counter(&self) -> ProgramInde
random
[ { "content": "/// Decode the next instruction in the Program stream\n\npub fn decode_next_instruction(instructions: &Program, program_counter: &mut usize) -> Option<Result<Box<dyn Instruction>, InstructionDecodeError>> {\n\n // @todo: I am not super happy with this decoding scheme. It should probably grab th...
Rust
src/librustc/ich/impls_ty.rs
amsantavicca/rust
730e5ad04e23f30cc24e4b87dfd5da807325e243
use ich::StableHashingContext; use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHasherResult}; use std::hash as std_hash; use std::mem; use ty; impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::Ty<'tcx> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { let type_hash = hcx.tcx().type_id_hash(*self); type_hash.hash_stable(hcx, hasher); } } impl_stable_hash_for!(struct ty::ItemSubsts<'tcx> { substs }); impl<'a, 'tcx, T> HashStable<StableHashingContext<'a, 'tcx>> for ty::Slice<T> where T: HashStable<StableHashingContext<'a, 'tcx>> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { (&**self).hash_stable(hcx, hasher); } } impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::subst::Kind<'tcx> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { self.as_type().hash_stable(hcx, hasher); self.as_region().hash_stable(hcx, hasher); } } impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::Region { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { mem::discriminant(self).hash_stable(hcx, hasher); match *self { ty::ReErased | ty::ReStatic | ty::ReEmpty => { } ty::ReLateBound(db, ty::BrAnon(i)) => { db.depth.hash_stable(hcx, hasher); i.hash_stable(hcx, hasher); } ty::ReEarlyBound(ty::EarlyBoundRegion { index, name }) => { index.hash_stable(hcx, hasher); name.hash_stable(hcx, hasher); } ty::ReLateBound(..) | ty::ReFree(..) | ty::ReScope(..) | ty::ReVar(..) | ty::ReSkolemized(..) => { bug!("TypeIdHasher: unexpected region {:?}", *self) } } } } impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::adjustment::AutoBorrow<'tcx> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { mem::discriminant(self).hash_stable(hcx, hasher); match *self { ty::adjustment::AutoBorrow::Ref(ref region, mutability) => { region.hash_stable(hcx, hasher); mutability.hash_stable(hcx, hasher); } ty::adjustment::AutoBorrow::RawPtr(mutability) => { mutability.hash_stable(hcx, hasher); } } } } impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::adjustment::Adjust<'tcx> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { mem::discriminant(self).hash_stable(hcx, hasher); match *self { ty::adjustment::Adjust::NeverToAny | ty::adjustment::Adjust::ReifyFnPointer | ty::adjustment::Adjust::UnsafeFnPointer | ty::adjustment::Adjust::ClosureFnPointer | ty::adjustment::Adjust::MutToConstPointer => {} ty::adjustment::Adjust::DerefRef { autoderefs, ref autoref, unsize } => { autoderefs.hash_stable(hcx, hasher); autoref.hash_stable(hcx, hasher); unsize.hash_stable(hcx, hasher); } } } } impl_stable_hash_for!(struct ty::adjustment::Adjustment<'tcx> { kind, target }); impl_stable_hash_for!(struct ty::MethodCall { expr_id, autoderef }); impl_stable_hash_for!(struct ty::MethodCallee<'tcx> { def_id, ty, substs }); impl_stable_hash_for!(struct ty::UpvarId { var_id, closure_expr_id }); impl_stable_hash_for!(struct ty::UpvarBorrow<'tcx> { kind, region }); impl_stable_hash_for!(enum ty::BorrowKind { ImmBorrow, UniqueImmBorrow, MutBorrow }); impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::UpvarCapture<'tcx> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { mem::discriminant(self).hash_stable(hcx, hasher); match *self { ty::UpvarCapture::ByValue => {} ty::UpvarCapture::ByRef(ref up_var_borrow) => { up_var_borrow.hash_stable(hcx, hasher); } } } } impl_stable_hash_for!(struct ty::FnSig<'tcx> { inputs_and_output, variadic, unsafety, abi }); impl<'a, 'tcx, T> HashStable<StableHashingContext<'a, 'tcx>> for ty::Binder<T> where T: HashStable<StableHashingContext<'a, 'tcx>> + ty::fold::TypeFoldable<'tcx> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { hcx.tcx().anonymize_late_bound_regions(self).0.hash_stable(hcx, hasher); } } impl_stable_hash_for!(enum ty::ClosureKind { Fn, FnMut, FnOnce }); impl_stable_hash_for!(enum ty::Visibility { Public, Restricted(def_id), Invisible }); impl_stable_hash_for!(struct ty::TraitRef<'tcx> { def_id, substs }); impl_stable_hash_for!(struct ty::TraitPredicate<'tcx> { trait_ref }); impl_stable_hash_for!(tuple_struct ty::EquatePredicate<'tcx> { t1, t2 }); impl<'a, 'tcx, A, B> HashStable<StableHashingContext<'a, 'tcx>> for ty::OutlivesPredicate<A, B> where A: HashStable<StableHashingContext<'a, 'tcx>>, B: HashStable<StableHashingContext<'a, 'tcx>>, { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { let ty::OutlivesPredicate(ref a, ref b) = *self; a.hash_stable(hcx, hasher); b.hash_stable(hcx, hasher); } } impl_stable_hash_for!(struct ty::ProjectionPredicate<'tcx> { projection_ty, ty }); impl_stable_hash_for!(struct ty::ProjectionTy<'tcx> { trait_ref, item_name }); impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::Predicate<'tcx> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { mem::discriminant(self).hash_stable(hcx, hasher); match *self { ty::Predicate::Trait(ref pred) => { pred.hash_stable(hcx, hasher); } ty::Predicate::Equate(ref pred) => { pred.hash_stable(hcx, hasher); } ty::Predicate::RegionOutlives(ref pred) => { pred.hash_stable(hcx, hasher); } ty::Predicate::TypeOutlives(ref pred) => { pred.hash_stable(hcx, hasher); } ty::Predicate::Projection(ref pred) => { pred.hash_stable(hcx, hasher); } ty::Predicate::WellFormed(ty) => { ty.hash_stable(hcx, hasher); } ty::Predicate::ObjectSafe(def_id) => { def_id.hash_stable(hcx, hasher); } ty::Predicate::ClosureKind(def_id, closure_kind) => { def_id.hash_stable(hcx, hasher); closure_kind.hash_stable(hcx, hasher); } } } } impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::AdtFlags { fn hash_stable<W: StableHasherResult>(&self, _: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { std_hash::Hash::hash(self, hasher); } } impl_stable_hash_for!(struct ty::VariantDef { did, name, discr, fields, ctor_kind }); impl_stable_hash_for!(enum ty::VariantDiscr { Explicit(def_id), Relative(distance) }); impl_stable_hash_for!(struct ty::FieldDef { did, name, vis }); impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ::middle::const_val::ConstVal<'tcx> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { use middle::const_val::ConstVal; mem::discriminant(self).hash_stable(hcx, hasher); match *self { ConstVal::Float(ref value) => { value.hash_stable(hcx, hasher); } ConstVal::Integral(ref value) => { value.hash_stable(hcx, hasher); } ConstVal::Str(ref value) => { value.hash_stable(hcx, hasher); } ConstVal::ByteStr(ref value) => { value.hash_stable(hcx, hasher); } ConstVal::Bool(value) => { value.hash_stable(hcx, hasher); } ConstVal::Function(def_id, substs) => { def_id.hash_stable(hcx, hasher); substs.hash_stable(hcx, hasher); } ConstVal::Struct(ref _name_value_map) => { panic!("Ordering still unstable") } ConstVal::Tuple(ref value) => { value.hash_stable(hcx, hasher); } ConstVal::Array(ref value) => { value.hash_stable(hcx, hasher); } ConstVal::Repeat(ref value, times) => { value.hash_stable(hcx, hasher); times.hash_stable(hcx, hasher); } ConstVal::Char(value) => { value.hash_stable(hcx, hasher); } } } } impl_stable_hash_for!(struct ty::ClosureSubsts<'tcx> { substs }); impl_stable_hash_for!(struct ty::GenericPredicates<'tcx> { parent, predicates }); impl_stable_hash_for!(enum ty::Variance { Covariant, Invariant, Contravariant, Bivariant }); impl_stable_hash_for!(enum ty::adjustment::CustomCoerceUnsized { Struct(index) }); impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::Generics { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { let ty::Generics { parent, parent_regions, parent_types, ref regions, ref types, type_param_to_index: _, has_self, } = *self; parent.hash_stable(hcx, hasher); parent_regions.hash_stable(hcx, hasher); parent_types.hash_stable(hcx, hasher); regions.hash_stable(hcx, hasher); types.hash_stable(hcx, hasher); has_self.hash_stable(hcx, hasher); } } impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::RegionParameterDef { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { let ty::RegionParameterDef { name, def_id, index, issue_32330: _, pure_wrt_drop } = *self; name.hash_stable(hcx, hasher); def_id.hash_stable(hcx, hasher); index.hash_stable(hcx, hasher); pure_wrt_drop.hash_stable(hcx, hasher); } } impl_stable_hash_for!(struct ty::TypeParameterDef { name, def_id, index, has_default, object_lifetime_default, pure_wrt_drop }); impl<'a, 'tcx, T> HashStable<StableHashingContext<'a, 'tcx>> for ::middle::resolve_lifetime::Set1<T> where T: HashStable<StableHashingContext<'a, 'tcx>> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { use middle::resolve_lifetime::Set1; mem::discriminant(self).hash_stable(hcx, hasher); match *self { Set1::Empty | Set1::Many => { } Set1::One(ref value) => { value.hash_stable(hcx, hasher); } } } } impl_stable_hash_for!(enum ::middle::resolve_lifetime::Region { Static, EarlyBound(index, decl), LateBound(db_index, decl), LateBoundAnon(db_index, anon_index), Free(call_site_scope_data, decl) }); impl_stable_hash_for!(struct ::middle::region::CallSiteScopeData { fn_id, body_id }); impl_stable_hash_for!(struct ty::DebruijnIndex { depth });
use ich::StableHashingContext; use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHasherResult}; use std::hash as std_hash; use std::mem; use ty; impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::Ty<'tcx> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { let type_hash = hcx.tcx().type_id_hash(*self); type_hash.hash_stable(hcx, hasher); } } impl_stable_hash_for!(struct ty::ItemSubsts<'tcx> { substs }); impl<'a, 'tcx, T> HashStable<StableHashingContext<'a, 'tcx>> for ty::Slice<T> where T: HashStable<StableHashingContext<'a, 'tcx>> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { (&**self).hash_stable(hcx, hasher); } } impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::subst::Kind<'tcx> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { self.as_type().hash_stable(hcx, hasher); self.as_region().hash_stable(hcx, hasher); } } impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::Region { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { mem::discriminant(self).hash_stable(hcx, hasher); match *self { ty::ReErased | ty::ReStatic | ty::ReEmpty => { } ty::ReLateBound(db, ty::BrAnon(i)) => { db.depth.hash_stable(hcx, hasher); i.hash_stable(hcx, hasher); } ty::ReEarlyBound(ty::EarlyBoundRegion { index, name }) => { index.hash_stable(hcx, hasher); name.hash_stable(hcx, hasher); } ty::ReLateBound(..) | ty::ReFree(..) | ty::ReScope(..) | ty::ReVar(..) | ty::ReSkolemized(..) => { bug!("TypeIdHasher: unexpected region {:?}", *self) } } } } impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::adjustment::AutoBorrow<'tcx> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { mem::discriminant(self).hash_stable(hcx, hasher); match *self { ty::adjustment::AutoBorrow::Ref(ref region, mutability) => { region.hash_stable(hcx, hasher); mutability.hash_stable(hcx, hasher); } ty::adjustment::AutoBorrow::RawPtr(mutability) => { mutability.hash_stable(hcx, hasher); } } } } impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::adjustment::Adjust<'tcx> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { mem::discriminant(self).hash_stable(hcx, hasher); match *self { ty::adjustment::Adjust::NeverToAny | ty::adjustment::Adjust::ReifyFnPointer | ty::adjustment::Adjust::UnsafeFnPointer | ty::adjustment::Adjust::ClosureFnPointer | ty::adjustment::Adjust::MutToConstPointer => {} ty::adjustment::Adjust::DerefRef { autoderefs, ref autoref, unsize } => { autoderefs.hash_stable(hcx, hasher); autoref.hash_stable(hcx, hasher); unsize.hash_stable(hcx, hasher); } } } } impl_stable_hash_for!(struct ty::adjustment::Adjustment<'tcx> { kind, target }); impl_stable_hash_for!(struct ty::MethodCall { expr_id, autoderef }); impl_stable_hash_for!(struct ty::MethodCallee<'tcx> { def_id, ty, substs }); impl_stable_hash_for!(struct ty::UpvarId { var_id, closure_expr_id }); impl_stable_hash_for!(struct ty::UpvarBorrow<'tcx> { kind, region }); impl_stable_hash_for!(enum ty::BorrowKind { ImmBorrow, UniqueImmBorrow, MutBorrow }); impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::UpvarCapture<'tcx> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { mem::discriminant(self).hash_stable(hcx, hasher); match *self { ty::UpvarCapture::ByValue => {} ty::UpvarCapture::ByRef(ref up_var_borrow) => { up_var_borrow.hash_stable(hcx, hasher); } } } } impl_stable_hash_for!(struct ty::FnSig<'tcx> { inputs_and_output, variadic, unsafety, abi }); impl<'a, 'tcx, T> HashStable<StableHashingContext<'a, 'tcx>> for ty::Binder<T> where T: HashStable<StableHashingContext<'a, 'tcx>> + ty::fold::TypeFoldable<'tcx> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { hcx.tcx().anonymize_late_bound_regions(self).0.hash_stable(hcx, hasher); } } impl_stable_hash_for!(enum ty::ClosureKind { Fn, FnMut, FnOnce }); impl_stable_hash_for!(enum ty::Visibility { Public, Restricted(def_id), Invisible }); impl_stable_hash_for!(struct ty::TraitRef<'tcx> { def_id, substs }); impl_stable_hash_for!(struct ty::TraitPredicate<'tcx> { trait_ref }); impl_stable_hash_for!(tuple_struct ty::EquatePredicate<'tcx> { t1, t2 }); impl<'a, 'tcx, A, B> HashStable<StableHashingContext<'a, 'tcx>> for ty::OutlivesPredicate<A, B> where A: HashStable<StableHashingContext<'a, 'tcx>>, B: HashStable<StableHashingContext<'a, 'tcx>>, { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { let ty::OutlivesPredicate(ref a, ref b) = *self; a.hash_stable(hcx, hasher); b.hash_stable(hcx, hasher); } } impl_stable_hash_for!(struct ty::ProjectionPredicate<'tcx> { projection_ty, ty }); impl_stable_hash_for!(struct ty::ProjectionTy<'tcx> { trait_ref, item_name }); impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::Predicate<'tcx> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { mem::discriminant(self).hash_stable(hcx, hasher); match *self { ty::Predicate::Trait(ref pred) => { pred.hash_stable(hcx, hasher); } ty::Predicate::Equate(ref pred) => { pred.hash_stable(hcx, hasher); } ty::Predicate::RegionOutlives(ref pred) => { pred.hash_stable(hcx, hasher); } ty::Predicate::TypeOutlives(ref pred) => { pred.hash_stable(hcx, hasher); } ty::Predicate::Projection(ref pred) => { pred.hash_stable(hcx, hasher); } ty::Predicate::WellFormed(ty) => { ty.hash_stable(hcx, hasher); } ty::Predicate::ObjectSafe(def_id) => { def_id.hash_stable(hcx, hasher); } ty::Predicate::ClosureKind(def_id, closure_kind) => { def_id.hash_stable(hcx, hasher); closure_kind.hash_stable(hcx, hasher); } } } } impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::AdtFlags { fn hash_stable<W: StableHasherResult>(&self, _: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { std_hash::Hash::hash(self, hasher); } } impl_stable_hash_for!(struct ty::VariantDef { did, name, discr, fields, ctor_kind }); impl_stable_hash_for!(enum ty::VariantDiscr { Explicit(def_id), Relative(distance) }); impl_stable_hash_for!(struct ty::FieldDef { did, name, vis }); impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ::middle::const_val::ConstVal<'tcx> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { use middle::const_val::ConstVal; mem::discriminant(self).hash_stable(hcx, hasher); match *self { ConstVal::Float(ref value) => { value.hash_stable(hcx, hasher); } ConstVal::Integral(ref value) => { value.hash_stable(hcx, hasher); } ConstVal::Str(ref value) => { value.hash_stable(hcx, hasher); } ConstVal::ByteStr(ref value) => { value.hash_stable(hcx, hasher); } ConstVal::Bool(value) => { value.hash_stable(hcx, hasher); } ConstVal::Function(def_id, substs) => { def_id.hash_stable(hcx, hasher); substs.hash_stable(hcx, hasher); } ConstVal::Struct(ref _name_value_map) => { panic!("Ordering still unstable") } ConstVal::Tuple(ref value) => { value.hash_stable(hcx, hasher); } ConstVal::Array(ref value) => { value.hash_stable(hcx, hasher); } ConstVal::Repeat(ref value, times) => { value.hash_stable(hcx, hasher); times.hash_stable(hcx, hasher); } ConstVal::Char(value) => { value.hash_stable(hcx, hasher); } } } } impl_stable_hash_for!(struct ty::ClosureSubsts<'tcx> { substs }); impl_stable_hash_for!(struct ty::GenericPredicates<'tcx> { parent, predicates }); impl_stable_hash_for!(enum ty::Variance { Covariant, Invariant, Contravariant, Bivariant }); impl_stable_hash_for!(enum ty::adjustment::CustomCoerceUnsized { Struct(index) }); impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::Generics { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { let ty::Generics { parent, parent_regions, parent_types, ref regions, ref types, type_param_to_index: _, has_self, } = *self; parent.hash_stable(hcx, hasher); parent_regions.hash_stable(hcx, hasher); parent_types.hash_stable(hcx, hasher); regions.hash_stable(hcx, hasher); types.hash_stable(hcx, hasher); has_self.hash_stable(hcx, hasher); } } impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::RegionParameterDef { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { let ty::RegionParameterDef { name, def_id, index,
} impl_stable_hash_for!(struct ty::TypeParameterDef { name, def_id, index, has_default, object_lifetime_default, pure_wrt_drop }); impl<'a, 'tcx, T> HashStable<StableHashingContext<'a, 'tcx>> for ::middle::resolve_lifetime::Set1<T> where T: HashStable<StableHashingContext<'a, 'tcx>> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'a, 'tcx>, hasher: &mut StableHasher<W>) { use middle::resolve_lifetime::Set1; mem::discriminant(self).hash_stable(hcx, hasher); match *self { Set1::Empty | Set1::Many => { } Set1::One(ref value) => { value.hash_stable(hcx, hasher); } } } } impl_stable_hash_for!(enum ::middle::resolve_lifetime::Region { Static, EarlyBound(index, decl), LateBound(db_index, decl), LateBoundAnon(db_index, anon_index), Free(call_site_scope_data, decl) }); impl_stable_hash_for!(struct ::middle::region::CallSiteScopeData { fn_id, body_id }); impl_stable_hash_for!(struct ty::DebruijnIndex { depth });
issue_32330: _, pure_wrt_drop } = *self; name.hash_stable(hcx, hasher); def_id.hash_stable(hcx, hasher); index.hash_stable(hcx, hasher); pure_wrt_drop.hash_stable(hcx, hasher); }
function_block-function_prefix_line
[ { "content": "trait Trait2<T1, T2> { fn dummy(&self, _: T1, _:T2) { } }\n\n\n\nimpl Trait1 for isize {}\n\nimpl<T1, T2> Trait2<T1, T2> for isize {}\n\n\n", "file_path": "src/test/debuginfo/type-names.rs", "rank": 0, "score": 563144.9302896057 }, { "content": "// We push types on the stack in...
Rust
src/cast/mod.rs
RottenFishbone/mucaster
9a3e1395e6ae942422d29250e7169547e9ca49e2
#![allow(dead_code, unused_variables)] pub mod error; use error::CastError; use mdns::{Record, RecordKind}; use futures_util::{pin_mut, stream::StreamExt}; use regex::Regex; use serde::{Serialize, ser::SerializeStruct}; use warp::hyper::{Client, body::HttpBody}; use std::{future, net::{IpAddr, UdpSocket}, sync::{mpsc::{Sender, TryRecvError}, Mutex, Arc}, thread, time::{SystemTime, Duration}}; use rust_cast::{CastDevice, ChannelMessage, channels::media::MediaResponse}; use rust_cast::channels::{ heartbeat::HeartbeatResponse, media::{Media, StatusEntry, StreamType}, receiver::CastDeviceApp, }; pub type Error = error::CastError; const DESTINATION_ID: &'static str = "receiver-0"; const SERVICE_NAME: &'static str = "_googlecast._tcp.local"; const TIMEOUT_SECONDS: u64 = 3; const STATUS_UPDATE_INTERVAL: u128 = 500; #[derive(Debug, Clone)] pub enum MediaStatus { Active(StatusEntry), Inactive, } impl From<StatusEntry> for MediaStatus { fn from(entry: StatusEntry) -> Self { MediaStatus::Active(entry) } } impl Serialize for MediaStatus { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer { let mut state; match self { MediaStatus::Inactive => { state = serializer.serialize_struct("status", 1).unwrap(); state.serialize_field("playbackState", "Inactive").unwrap(); state.end() } MediaStatus::Active(entry) => { let mut num_fields = 1; if entry.current_time.is_some() { num_fields += 1; } if let Some(media) = &entry.media { if media.duration.is_some() { num_fields += 1; } } state = serializer.serialize_struct("status", num_fields).unwrap(); state.serialize_field("playbackState", &entry.player_state.to_string()).unwrap(); if let Some(media) = &entry.media { state.serialize_field("videoLength", &media.duration.unwrap()).unwrap(); } if let Some(time) = &entry.current_time { state.serialize_field("currentTime", time).unwrap(); } state.end() } } } } enum PlayerSignal { Play, Pause, Stop, Seek(f32), } pub struct Caster { device_addr: Option<String>, shutdown_tx: Option<Sender<()>>, pub status: Arc<Mutex<MediaStatus>>, } impl Drop for Caster { fn drop(&mut self) { self.close(); } } impl Caster { pub fn new() -> Self { Self { device_addr: None, shutdown_tx: None, status: Arc::from(Mutex::from(MediaStatus::Inactive)), } } pub fn is_streaming(&self) -> bool { let is_active = match self.status.lock().unwrap().clone() { MediaStatus::Inactive => false, _ => true, }; self.device_addr.is_some() && is_active } pub fn set_device_addr(&mut self, addr: &str) { self.device_addr = Some(addr.into()); } pub fn close(&mut self) { if self.is_streaming() { self.stop().unwrap(); } if let Some(sender) = &self.shutdown_tx { let _ = sender.send(()); self.shutdown_tx = None; } } pub fn begin_cast(&mut self, media_port: u16) -> Result<(), CastError> { let addr = match &self.device_addr { Some(addr) => addr.clone(), None => { return Err(CastError::CasterError("No device address selected.")); } }; let (shutdown_tx, shutdown_rx) = std::sync::mpsc::channel::<()>(); self.shutdown_tx = Some(shutdown_tx); let status_ref = self.status.clone(); let mut last_media_status = SystemTime::now(); let mut status_delay = 5000; let handle = thread::spawn(move || { let device = CastDevice::connect_without_host_verification(addr, 8009).unwrap(); device.connection.connect(DESTINATION_ID).unwrap(); log::info!("[Chromecast] Connected to device"); let app = device.receiver.launch_app( &CastDeviceApp::DefaultMediaReceiver).unwrap(); let transport_id = app.transport_id.to_string(); let session_id = app.session_id.to_string(); log::info!("[Chromecast] Launched media app."); let media_addr = format!("http://{}:{}", get_local_ip().unwrap(), media_port); device.connection.connect(&transport_id).unwrap(); device.media.load( &transport_id, &session_id, &Media { content_id: media_addr, content_type: "video/mp4".to_string(), stream_type: StreamType::None, duration: None, metadata: None, }, ).unwrap(); log::info!("[Chromecast] Loaded media."); loop { match shutdown_rx.try_recv() { Ok(_) | Err(TryRecvError::Disconnected) => { log::info!("[Chromecast] Closing comm thread."); return; }, Err(TryRecvError::Empty) => {} } if let Some((ch_msg, msg)) = Caster::handle_device_status(&device){ log::info!("[Device Message] {}", &msg); } let millis_since_last = last_media_status .elapsed().unwrap() .as_millis(); if millis_since_last >= status_delay { status_delay = STATUS_UPDATE_INTERVAL; let statuses = match device.media .get_status(&transport_id, None) { Ok(statuses) => statuses, Err(err) => { log::info!("[Chromecast] Error: {:?}", err); continue; }, }; let status = match statuses.entries.first() { Some(status) => MediaStatus::Active(status.clone()), None => MediaStatus::Inactive }; log::info!("[Chromecast] [Status] {:?}", &status); *status_ref.lock().unwrap() = status; last_media_status = SystemTime::now(); } } }); Ok(()) } fn handle_device_status(device: &CastDevice) -> Option<(ChannelMessage, String)> { match device.receive() { Ok(msg) => { let log_msg: String; match &msg { ChannelMessage::Connection(resp) => { return Some((msg.clone(), format!("[Device=>Connection] {:?}", resp))); } ChannelMessage::Media(resp) => { Self::handle_media_status(resp); return Some((msg.clone(), format!("[Device=>Media] {:?}", resp))); } ChannelMessage::Receiver(resp) => { return Some((msg.clone(), format!("[Device=>Receiver] {:?}", resp))); } ChannelMessage::Raw(resp) => { return Some((msg.clone(), format!("[Device] Message could not be parsed: {:?}", resp))); } ChannelMessage::Heartbeat(resp) => { if let HeartbeatResponse::Ping = resp { device.heartbeat.pong().unwrap(); log::info!("[Heartbeat] Pong sent."); } return Some((msg.clone(), (format!("[Heartbeat] {:?}", resp)))); } } }, Err(err) => { log::error!("An error occured while recieving message from chromecast:\n{:?}", err); return None } } } fn handle_media_status(resp: &MediaResponse) { let status = match resp { MediaResponse::Status(status) => status.clone(), _=> {return;} }; } pub fn resume(&self) -> Result<(), CastError> { self.change_media_state(PlayerSignal::Play)?; Ok(()) } pub fn pause(&self) -> Result<(), CastError> { self.change_media_state(PlayerSignal::Pause)?; Ok(()) } pub fn stop(&self) -> Result<(), CastError> { self.change_media_state(PlayerSignal::Stop)?; Ok(()) } pub fn seek(&self, time: f32) -> Result<(), CastError> { self.change_media_state(PlayerSignal::Seek(time))?; Ok(()) } fn change_media_state(&self, state: PlayerSignal) -> Result<(),CastError> { let device = self.connect()?; let status = device.receiver.get_status()?; let app = status.applications.first().unwrap(); device.connection.connect(app.transport_id.to_string())?; let media_status = device.media .get_status( app.transport_id.as_str(), None)?; if let Some(media_status) = media_status.entries.first(){ let transport_id = app.transport_id.as_str(); let session_id = media_status.media_session_id; match state { PlayerSignal::Play => { device.media.play(transport_id, session_id)?; } PlayerSignal::Pause => { device.media.pause(transport_id, session_id)?; } PlayerSignal::Stop => { device.media.stop(transport_id, session_id)?; } PlayerSignal::Seek(time) => { device.media.seek( transport_id, session_id, Some(time), None)?; } } }else{ return Err(CastError::CasterError( "Cannot change media state. No active media.")); } device.connection.disconnect(DESTINATION_ID).unwrap(); Ok(()) } fn connect(&self) -> Result<CastDevice, CastError> { let addr = match &self.device_addr { Some(addr) => addr.clone(), None => { return Err(CastError::CasterError("No device address set.")); } }; let device = match CastDevice::connect_without_host_verification( addr, 8009){ Ok(device) => device, Err(err) => { panic!("Failed to establish connection to device: {:?}", err); } }; device.connection.connect(DESTINATION_ID).unwrap(); Ok(device) } } pub async fn find_chromecasts() -> Result<Vec<(String, IpAddr)>, CastError> { let timeout = Duration::from_secs(TIMEOUT_SECONDS); let start_time = SystemTime::now(); let stream = mdns::discover::all(SERVICE_NAME, timeout)? .listen() .take_while(|_|future::ready(start_time.elapsed().unwrap() < timeout)); pin_mut!(stream); let mut device_ips = Vec::new(); while let Some(Ok(resp)) = stream.next().await { let addr = resp.records() .find_map(self::to_ip_addr); if let Some(addr) = addr { if !device_ips.contains(&addr) { device_ips.push(addr.clone()); } } } let client = Client::new(); let mut chromecasts = Vec::<(String, IpAddr)>::new(); for ip in device_ips { let uri = format!("http://{}:8008/ssdp/device-desc.xml", ip) .parse() .unwrap(); if let Ok(mut resp) = client.get(uri).await { if resp.status().is_success() { if let Some(body) = resp.body_mut().data().await { if let Ok(body) = body { let body = body.to_vec(); let body_string = String::from_utf8(body).unwrap(); let reg = Regex::new(r#"<friendlyName>(.*)</friendlyName>"#).unwrap(); let captures = reg.captures(&body_string); if let Some(captures) = captures { if let Some(capture) = captures.get(1) { chromecasts.push((capture.as_str().into(), ip)); continue; } } } } } } chromecasts.push((String::from("Unknown"), ip)); } Ok(chromecasts) } fn to_ip_addr(record: &Record) -> Option<IpAddr> { match record.kind { RecordKind::A(addr) => Some(addr.into()), RecordKind::AAAA(addr) => Some(addr.into()), _ => None, } } fn get_local_ip() -> Result<String, std::io::Error> { let socket = UdpSocket::bind("0.0.0.0:0")?; socket.connect("8.8.8.8:80")?; Ok(socket.local_addr()?.ip().to_string()) }
#![allow(dead_code, unused_variables)] pub mod error; use error::CastError; use mdns::{Record, RecordKind}; use futures_util::{pin_mut, stream::StreamExt}; use regex::Regex; use serde::{Serialize, ser::SerializeStruct}; use warp::hyper::{Client, body::HttpBody}; use std::{future, net::{IpAddr, UdpSocket}, sync::{mpsc::{Sender, TryRecvError}, Mutex, Arc}, thread, time::{SystemTime, Duration}}; use rust_cast::{CastDevice, ChannelMessage, channels::media::MediaResponse}; use rust_cast::channels::{ heartbeat::HeartbeatResponse, media::{Media, StatusEntry, StreamType}, receiver::CastDeviceApp, }; pub type Error = error::CastError; const DESTINATION_ID: &'static str = "receiver-0"; const SERVICE_NAME: &'static str = "_googlecast._tcp.local"; const TIMEOUT_SECONDS: u64 = 3; const STATUS_UPDATE_INTERVAL: u128 = 500; #[derive(Debug, Clone)] pub enum MediaStatus { Active(StatusEntry), Inactive, } impl From<StatusEntry> for MediaStatus { fn from(entry: StatusEntry) -> Self { MediaStatus::Active(entry) } } impl Serialize for MediaStatus { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer { let mut state; match self { MediaStatus::Inactive => { state = serializer.serialize_struct("status", 1).unwrap(); state.serialize_field("playbackState", "Inactive").unwrap(); state.end() } MediaStatus::Active(entry) => { let mut num_fields = 1; if entry.current_time.is_some() { num_fields += 1; } if let Some(media) = &entry.media { if media.duration.is_some() { num_fields += 1; } } state = serializer.serialize_struct("status", num_fields).unwrap(); state.serialize_field("playbackState", &entry.player_state.to_string()).unwrap(); if let Some(media) = &entry.media { state.serialize_field("videoLength", &media.duration.unwrap()).unwrap(); } if let Some(time) = &entry.current_time { state.serialize_field("currentTime", time).unwrap(); } state.end() } } } } enum PlayerSignal { Play, Pause, Stop, Seek(f32), } pub struct Caster { device_addr: Option<String>, shutdown_tx: Option<Sender<()>>, pub status: Arc<Mutex<MediaStatus>>, } impl Drop for Caster { fn drop(&mut self) { self.close(); } } impl Caster { pub fn new() -> Self { Self { device_addr: None, shutdown_tx: None, status: Arc::from(Mutex::from(MediaStatus::Inactive)), } } pub fn is_streaming(&self) -> bool { let is_active = match self.status.lock().unwrap().clone() { MediaStatus::Inactive => false, _ => true, }; self.device_addr.is_some() && is_active } pub fn set_device_addr(&mut self, addr: &str) { self.device_addr = Some(addr.into()); } pub fn close(&mut self) { if self.is_streaming() { self.stop().unwrap(); } if let Some(sender) = &self.shutdown_tx { let _ = sender.send(()); self.shutdown_tx = None; } } pub fn begin_cast(&mut self, media_port: u16) -> Result<(), CastError> { let addr = match &self.device_addr { Some(addr) => addr.clone(), None => { return Err(CastError::CasterError("No device address selected.")); } }; let (shutdown_tx, shutdown_rx) = std::sync::mpsc::channel::<()>(); self.shutdown_tx = Some(shutdown_tx); let status_ref = self.status.clone(); let mut last_media_status = SystemTime::now(); let mut status_delay = 5000; let handle = thread::spawn(move || { let device = CastDevice::connect_without_host_verification(addr, 8009).unwrap(); device.connection.connect(DESTINATION_ID).unwrap(); log::info!("[Chromecast] Connected to device"); let app = device.receiver.launch_app( &CastDeviceApp::DefaultMediaReceiver).unwrap(); let transport_id = app.transport_id.to_string(); let session_id = app.session_id.to_string(); log::info!("[Chromecast] Launched media app."); let media_addr = format!("http://{}:{}", get_local_ip().unwrap(), media_port); device.connection.connect(&transport_id).unwrap(); device.media.load( &transport_id, &session_id, &Media { content_id: media_addr, content_type: "video/mp4".to_string(), stream_type: StreamType::None, duration: None, metadata: None, }, ).unwrap(); log::info!("[Chromecast] Loaded media."); loop { match shutdown_rx.try_recv() { Ok(_) | Err(TryRecvError::Disconnected) => { log::info!("[Chromecast] Closing comm thread."); return; }, Err(TryRecvError::Empty) => {} } if let Some((ch_msg, msg)) = Caster::handle_device_status(&device){ log::info!("[Device Message] {}", &msg); } let millis_since_last = last_media_status .elapsed().unwrap() .as_millis(); if millis_since_last >= status_delay { status_delay = STATUS_UPDATE_INTERVAL; let statuses = match device.media .get_status(&transport_id, None) { Ok(statuses) => statuses, Err(err) => { log::info!("[Chromecast] Error: {:?}", err); continue; }, }; let status = match statuses.entries.first() { Some(status) => MediaStatus::Active(status.clone()), None => MediaStatus::Inactive }; log::info!("[Chromecast] [Status] {:?}", &status); *status_ref.lock().unwrap() = status; last_media_status = SystemTime::now(); } } }); Ok(()) } fn handle_device_status(device: &CastDevice) -> Option<(ChannelMessage, String)> { match device.receive() { Ok(msg) => { let log_msg: String; match &msg { ChannelMessage::Connection(resp) => { return Some((msg.clone(), format!("[Device=>Connection] {:?}", resp))); } ChannelMessage::Media(resp) => { Self::handle_media_status(resp); return Some((msg.clone(), format!("[Device=>Media] {:?}", resp))); } ChannelMessage::Receiver(resp) => { return Some((msg.clone(), format!("[Device=>Receiver] {:?}", resp))); } ChannelMessage::Raw(resp) => { return
; } ChannelMessage::Heartbeat(resp) => { if let HeartbeatResponse::Ping = resp { device.heartbeat.pong().unwrap(); log::info!("[Heartbeat] Pong sent."); } return Some((msg.clone(), (format!("[Heartbeat] {:?}", resp)))); } } }, Err(err) => { log::error!("An error occured while recieving message from chromecast:\n{:?}", err); return None } } } fn handle_media_status(resp: &MediaResponse) { let status = match resp { MediaResponse::Status(status) => status.clone(), _=> {return;} }; } pub fn resume(&self) -> Result<(), CastError> { self.change_media_state(PlayerSignal::Play)?; Ok(()) } pub fn pause(&self) -> Result<(), CastError> { self.change_media_state(PlayerSignal::Pause)?; Ok(()) } pub fn stop(&self) -> Result<(), CastError> { self.change_media_state(PlayerSignal::Stop)?; Ok(()) } pub fn seek(&self, time: f32) -> Result<(), CastError> { self.change_media_state(PlayerSignal::Seek(time))?; Ok(()) } fn change_media_state(&self, state: PlayerSignal) -> Result<(),CastError> { let device = self.connect()?; let status = device.receiver.get_status()?; let app = status.applications.first().unwrap(); device.connection.connect(app.transport_id.to_string())?; let media_status = device.media .get_status( app.transport_id.as_str(), None)?; if let Some(media_status) = media_status.entries.first(){ let transport_id = app.transport_id.as_str(); let session_id = media_status.media_session_id; match state { PlayerSignal::Play => { device.media.play(transport_id, session_id)?; } PlayerSignal::Pause => { device.media.pause(transport_id, session_id)?; } PlayerSignal::Stop => { device.media.stop(transport_id, session_id)?; } PlayerSignal::Seek(time) => { device.media.seek( transport_id, session_id, Some(time), None)?; } } }else{ return Err(CastError::CasterError( "Cannot change media state. No active media.")); } device.connection.disconnect(DESTINATION_ID).unwrap(); Ok(()) } fn connect(&self) -> Result<CastDevice, CastError> { let addr = match &self.device_addr { Some(addr) => addr.clone(), None => { return Err(CastError::CasterError("No device address set.")); } }; let device = match CastDevice::connect_without_host_verification( addr, 8009){ Ok(device) => device, Err(err) => { panic!("Failed to establish connection to device: {:?}", err); } }; device.connection.connect(DESTINATION_ID).unwrap(); Ok(device) } } pub async fn find_chromecasts() -> Result<Vec<(String, IpAddr)>, CastError> { let timeout = Duration::from_secs(TIMEOUT_SECONDS); let start_time = SystemTime::now(); let stream = mdns::discover::all(SERVICE_NAME, timeout)? .listen() .take_while(|_|future::ready(start_time.elapsed().unwrap() < timeout)); pin_mut!(stream); let mut device_ips = Vec::new(); while let Some(Ok(resp)) = stream.next().await { let addr = resp.records() .find_map(self::to_ip_addr); if let Some(addr) = addr { if !device_ips.contains(&addr) { device_ips.push(addr.clone()); } } } let client = Client::new(); let mut chromecasts = Vec::<(String, IpAddr)>::new(); for ip in device_ips { let uri = format!("http://{}:8008/ssdp/device-desc.xml", ip) .parse() .unwrap(); if let Ok(mut resp) = client.get(uri).await { if resp.status().is_success() { if let Some(body) = resp.body_mut().data().await { if let Ok(body) = body { let body = body.to_vec(); let body_string = String::from_utf8(body).unwrap(); let reg = Regex::new(r#"<friendlyName>(.*)</friendlyName>"#).unwrap(); let captures = reg.captures(&body_string); if let Some(captures) = captures { if let Some(capture) = captures.get(1) { chromecasts.push((capture.as_str().into(), ip)); continue; } } } } } } chromecasts.push((String::from("Unknown"), ip)); } Ok(chromecasts) } fn to_ip_addr(record: &Record) -> Option<IpAddr> { match record.kind { RecordKind::A(addr) => Some(addr.into()), RecordKind::AAAA(addr) => Some(addr.into()), _ => None, } } fn get_local_ip() -> Result<String, std::io::Error> { let socket = UdpSocket::bind("0.0.0.0:0")?; socket.connect("8.8.8.8:80")?; Ok(socket.local_addr()?.ip().to_string()) }
Some((msg.clone(), format!("[Device] Message could not be parsed: {:?}", resp)))
call_expression
[ { "content": "/// Spin and wait for a response from the passed reciever.\n\n/// # Parameters\n\n/// oneshot::Receiver<String> - A reciever, with the sender linked to the api::Request\n\n/// # Returns\n\n/// Result<String, String> - API response on success, \"Failed to reach API\" on failure. \n\npub fn await_ap...
Rust
dora/src/vm/modules.rs
dinfuehr/dora
bcfdac576b729e2bbb2422d0239426b884059b2c
use parking_lot::RwLock; use std::sync::Arc; use crate::semck::specialize::replace_type_param; use crate::size::InstanceSize; use crate::ty::SourceType; use crate::utils::GrowableVec; use crate::vm::{ accessible_from, namespace_path, Candidate, FctId, Field, FieldDef, FileId, NamespaceId, TraitId, VM, }; use crate::vtable::VTableBox; use dora_parser::ast; use dora_parser::interner::Name; use dora_parser::lexer::position::Position; use std::collections::HashSet; #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct ModuleId(usize); impl ModuleId { pub fn max() -> ModuleId { ModuleId(usize::max_value()) } } impl From<ModuleId> for usize { fn from(data: ModuleId) -> usize { data.0 } } impl From<usize> for ModuleId { fn from(data: usize) -> ModuleId { ModuleId(data) } } impl GrowableVec<RwLock<Module>> { pub fn idx(&self, index: ModuleId) -> Arc<RwLock<Module>> { self.idx_usize(index.0) } } pub static DISPLAY_SIZE: usize = 6; #[derive(Debug)] pub struct Module { pub id: ModuleId, pub file_id: FileId, pub ast: Arc<ast::Module>, pub namespace_id: NamespaceId, pub pos: Position, pub name: Name, pub ty: SourceType, pub parent_class: Option<SourceType>, pub internal: bool, pub internal_resolved: bool, pub has_constructor: bool, pub is_pub: bool, pub constructor: Option<FctId>, pub fields: Vec<Field>, pub methods: Vec<FctId>, pub virtual_fcts: Vec<FctId>, pub traits: Vec<TraitId>, } impl Module { pub fn name(&self, vm: &VM) -> String { namespace_path(vm, self.namespace_id, self.name) } } pub fn find_methods_in_module(vm: &VM, object_type: SourceType, name: Name) -> Vec<Candidate> { let mut ignores = HashSet::new(); let mut module_type = object_type; loop { let module_id = module_type.module_id().expect("no module"); let module = vm.modules.idx(module_id); let module = module.read(); for &method in &module.methods { let method = vm.fcts.idx(method); let method = method.read(); if method.name == name { if let Some(overrides) = method.overrides { ignores.insert(overrides); } if !ignores.contains(&method.id) { return vec![Candidate { object_type: module_type.clone(), container_type_params: module_type.type_params(vm), fct_id: method.id, }]; } } } if let Some(parent_class) = module.parent_class.clone() { let type_list = module_type.type_params(vm); module_type = replace_type_param(vm, parent_class, &type_list, None); } else { break; } } Vec::new() } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct ModuleDefId(usize); impl ModuleDefId { pub fn to_usize(self) -> usize { self.0 } } impl From<usize> for ModuleDefId { fn from(data: usize) -> ModuleDefId { ModuleDefId(data) } } impl GrowableVec<RwLock<ModuleDef>> { pub fn idx(&self, index: ModuleDefId) -> Arc<RwLock<ModuleDef>> { self.idx_usize(index.0) } } #[derive(Debug)] pub struct ModuleDef { pub id: ModuleDefId, pub mod_id: Option<ModuleId>, pub parent_id: Option<ModuleDefId>, pub fields: Vec<FieldDef>, pub size: InstanceSize, pub ref_fields: Vec<i32>, pub vtable: Option<VTableBox>, } impl ModuleDef { pub fn name(&self, vm: &VM) -> String { if let Some(module_id) = self.mod_id { let module = vm.modules.idx(module_id); let module = module.read(); let name = vm.interner.str(module.name); format!("{}", name) } else { "<Unknown>".into() } } } pub fn module_accessible_from(vm: &VM, module_id: ModuleId, namespace_id: NamespaceId) -> bool { let module = vm.modules.idx(module_id); let module = module.read(); accessible_from(vm, module.namespace_id, module.is_pub, namespace_id) }
use parking_lot::RwLock; use std::sync::Arc; use crate::semck::specialize::replace_type_param; use crate::size::InstanceSize; use crate::ty::SourceType; use crate::utils::GrowableVec; use crate::vm::{ accessible_from, namespace_path, Candidate, FctId, Field, FieldDef, FileId, NamespaceId, TraitId, VM, }; use crate::vtable::VTableBox; use dora_parser::ast; use dora_parser::interner::Name; use dora_parser::lexer::position::Position; use std::collections::HashSet; #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct ModuleId(usize); impl ModuleId { pub fn max() -> ModuleId { ModuleId(usize::max_value()) } } impl From<ModuleId> for usize { fn from(data: ModuleId) -> usize { data.0 } } impl From<usize> for ModuleId { fn from(data: usize) -> ModuleId { ModuleId(data) } } impl GrowableVec<RwLock<Module>> { pub fn idx(&self, index: ModuleId) -> Arc<RwLock<Module>> { self.idx_usize(index.0) } } pub static DISPLAY_SIZE: usize = 6; #[derive(Debug)] pub struct Module { pub id: ModuleId, pub file_id: FileId, pub ast: Arc<ast::Module>, pub namespace_id: NamespaceId, pub pos: Position, pub name: Name, pub ty: SourceType, pub parent_class: Option<SourceType>, pub internal: bool, pub internal_resolved: bool, pub has_constructor: bool, pub is_pub: bool, pub constructor: Option<FctId>, pub fields: Vec<Field>, pub methods: Vec<FctId>, pub virtual_fcts: Vec<FctId>, pub traits: Vec<TraitId>, } impl Module { pub fn name(&self, vm: &VM) -> String { namespace_path(vm, self.namespace_id, self.name) } } pub fn find_methods_in_module(vm: &VM, object_type: SourceType, name: Name) -> Vec<Candidate> { let mut ignores = HashSet::new(); let mut module_type = object_type; loop { let module_id = module_type.module_id().expect("no module"); let module = vm.modules.idx(module_id); let module = module.read(); for &method in &module.methods { let method = vm.fcts.idx(method); let method = method.read(); if method.name == name { if let Some(overrides) = method.overrides { ignores.insert(overrides); } if !ignores.contains(&method.id) { return vec![Candidate { object_type: module_type.clone(), container_type_params: module_type.type_params(vm), fct_id: method.id, }]; } } } if let Some(parent_class) = module.parent_class.clone() { let type_list = module_type.type_params(vm); module_type = replace_type_param(vm, parent_class, &type_list, None); } else { break; } } Vec::new() } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct ModuleDefId(usize); impl ModuleDefId { pub fn to_usize(self) -> usize { self.0 } } impl From<usize> for ModuleDefId { fn from(data: usize) -> ModuleDefId { ModuleDefId(data) } } impl GrowableVec<RwLock<ModuleDef>> { pub fn idx(&self, index: ModuleDefId) -> Arc<RwLock<ModuleDef>> { self.idx_usize(index.0) } } #[derive(Debug)] pub struct ModuleDef { pub id: ModuleDefId, pub mod_id: Option<ModuleId>, pub parent_id: Option<ModuleDefId>, pub fields: Vec<FieldDef>, pub size: InstanceSize, pub ref_fields: Vec<i32>, pub vtable: Option<VTableBox>, } impl ModuleDef {
} pub fn module_accessible_from(vm: &VM, module_id: ModuleId, namespace_id: NamespaceId) -> bool { let module = vm.modules.idx(module_id); let module = module.read(); accessible_from(vm, module.namespace_id, module.is_pub, namespace_id) }
pub fn name(&self, vm: &VM) -> String { if let Some(module_id) = self.mod_id { let module = vm.modules.idx(module_id); let module = module.read(); let name = vm.interner.str(module.name); format!("{}", name) } else { "<Unknown>".into() } }
function_block-full_function
[ { "content": "pub fn namespace_path(vm: &VM, namespace_id: NamespaceId, name: Name) -> String {\n\n let namespace = &vm.namespaces[namespace_id.to_usize()];\n\n let mut result = namespace.name(vm);\n\n\n\n if !result.is_empty() {\n\n result.push_str(\"::\");\n\n }\n\n\n\n result.push_str(&...
Rust
src/audio/channels/noise.rs
super-rust-boy/super-rust-boy
53555c60278359877a3a6fe4bb7175f129e803e6
use super::*; const MAX_LEN: u8 = 64; pub struct Noise { pub length_reg: u8, pub vol_envelope_reg: u8, pub poly_counter_reg: u8, pub trigger_reg: u8, enabled: bool, lfsr_counter: u16, volume: u8, volume_counter: Option<u8>, volume_modulo: u8, length_counter: u8, length_modulo: u8, freq_counter: u32, freq_modulo: u32, } impl Noise { pub fn new() -> Self { Self { length_reg: 0, vol_envelope_reg: 0, poly_counter_reg: 0, trigger_reg: 0, enabled: false, lfsr_counter: 0xFFFF, volume: 0, volume_counter: None, volume_modulo: 0, length_counter: 0, length_modulo: MAX_LEN, freq_counter: 0, freq_modulo: 0, } } pub fn set_length_reg(&mut self, val: u8) { self.length_reg = val; } pub fn set_vol_envelope_reg(&mut self, val: u8) { self.vol_envelope_reg = val; } pub fn set_poly_counter_reg(&mut self, val: u8) { self.poly_counter_reg = val; } pub fn set_trigger_reg(&mut self, val: u8) { if test_bit!(val, 7) { self.trigger(); } } pub fn is_enabled(&self) -> bool { self.enabled } } impl Channel for Noise { fn sample_clock(&mut self, cycles: u32) { self.freq_counter += cycles; if self.freq_counter >= self.freq_modulo { self.freq_counter -= self.freq_modulo; self.lfsr_step(); } } fn length_clock(&mut self) { if self.enabled && test_bit!(self.trigger_reg, 6) { self.length_counter -= 1; if self.length_counter == self.length_modulo { self.enabled = false; } } } fn envelope_clock(&mut self) { if let Some(counter) = self.volume_counter { let new_count = counter + 1; self.volume_counter = if new_count >= self.volume_modulo { match test_bit!(self.vol_envelope_reg, 3) { false if self.volume > MIN_VOL => { self.volume -= 1; Some(0) }, true if self.volume < MAX_VOL => { self.volume += 1; Some(0) }, _ => None } } else { Some(new_count) }; } } fn get_sample(&self) -> f32 { if self.enabled { if (self.lfsr_counter & 1) == 1 { -u4_to_f32(self.volume) } else { u4_to_f32(self.volume) } } else { 0.0 } } fn reset(&mut self) { self.length_reg = 0; self.vol_envelope_reg = 0; self.poly_counter_reg = 0; self.trigger_reg = 0; self.freq_counter = 0; self.length_counter = MAX_LEN; } } impl Noise { fn trigger(&mut self) { const LEN_MASK: u8 = bits![5, 4, 3, 2, 1, 0]; const VOL_MASK: u8 = bits![7, 6, 5, 4]; const VOL_SWEEP_MASK: u8 = bits![2, 1, 0]; const FREQ_SHIFT_MASK: u8 = bits![7, 6, 5, 4]; const FREQ_DIVISOR_MASK: u8 = bits![2, 1, 0]; self.volume = (self.vol_envelope_reg & VOL_MASK) >> 4; self.volume_modulo = self.vol_envelope_reg & VOL_SWEEP_MASK; self.volume_counter = if self.volume_modulo == 0 {None} else {Some(0)}; let freq_modulo_shift = (self.poly_counter_reg & FREQ_SHIFT_MASK) >> 4; self.freq_modulo = match self.poly_counter_reg & FREQ_DIVISOR_MASK { 0 => 8, x => (x as u32) * 16, } << freq_modulo_shift; self.freq_counter = 0; self.length_counter = MAX_LEN; self.length_modulo = self.length_reg & LEN_MASK; self.lfsr_counter = 0xFFFF; self.enabled = true; } fn lfsr_step(&mut self) { const LFSR_MASK: u16 = 0x3FFF; const LFSR_7BIT_MASK: u16 = 0xFFBF; let low_bit = self.lfsr_counter & 1; self.lfsr_counter >>= 1; let xor_bit = (self.lfsr_counter & 1) ^ low_bit; self.lfsr_counter = (self.lfsr_counter & LFSR_MASK) | (xor_bit << 14); if test_bit!(self.poly_counter_reg, 3) { self.lfsr_counter = (self.lfsr_counter & LFSR_7BIT_MASK) | (xor_bit << 6); } } }
use super::*; const MAX_LEN: u8 = 64; pub struct Noise { pub length_reg: u8, pub vol_envelope_reg: u8, pub poly_counter_reg: u8, pub trigger_reg: u8, enabled: bool, lfsr_counter: u16, volume: u8, volume_counter: Option<u8>, volume_modulo: u8, length_counter: u8, length_modulo: u8, freq_counter: u32, freq_modulo: u32, } impl Noise { pub fn new() -> Self { Self { length_reg: 0, vol_envelope_reg: 0, poly_counter_reg: 0, trigger_reg: 0, enabled: false, lfsr_counter: 0xFFFF, volume: 0, volume_counter: None, volume_modulo: 0, length_counter: 0, length_modulo: MAX_LEN, freq_counter: 0, freq_modulo: 0, } } pub fn set_length_reg(&mut self, val: u8) { self.length_reg = val; } pub fn set_vol_envelope_reg(&mut self, val: u8) { self.vol_envelope_reg = val; } pub fn set_poly_counter_reg(&mut self, val: u8) { self.poly_counter_reg = val; } pub fn set_trigger_reg(&mut self, val: u8) { if test_bit!(val, 7) { self.trigger(); } } pub fn is_enabled(&self) -> bool { self.enabled } } impl Channel for Noise { fn sample_clock(&mut self, cycles: u32) { self.freq_counter += cycles; if self.freq_counter >= self.freq_modulo { self.freq_counter -= self.freq_modulo; self.lfsr_step(); } } fn length_clock(&mut self) { if self.enabled && test_bit!(self.trigger_reg, 6) { self.length_counter -= 1; if self.length_counter == self.length_modulo { self.enabled = false; } } } fn envelope_clock(&mut self) { if let Some(counter) = self.volume_counter { let new_count = counter + 1; self.volume_counter = if new_count >= self.volume_modulo { match test_bit!(self.vol_envelope_reg, 3) { false if self.volume > MIN_VOL => { self.volume -= 1; Some(0) }, true if self.volume < MAX_VOL => { self.volume += 1; Some(0) }, _ => None } } else { Some(new_count) }; } } fn get_sample(&self) -> f32 { if self.enabled { if (self.lfsr_counter & 1) == 1 { -u4_to_f32(self.volume) } else { u4_to_f32(self.volume) } } else { 0.0 } } fn reset(&mut self) { self.length_reg = 0; self.vol_envelope_reg = 0; self.poly_counter_reg = 0; self.trigger_reg = 0; self.freq_counter = 0; self.length_counter = MAX_LEN; } } impl Noise { fn trigger(&mut self) { const LEN_MASK: u8 = bits![5, 4, 3, 2, 1, 0]; const VOL_MASK: u8 = bits![7, 6, 5, 4]; const VOL_SWEEP_MASK: u8 = bits![2, 1, 0]; const FREQ_SHIFT_MASK: u8 = bits![7, 6, 5, 4]; const FREQ_DIVISOR_MASK: u8 = bits![2, 1, 0]; self.volume = (self.vol_envelope_reg & VOL_MASK) >> 4; self.volume_modulo = self.vol_envelope_reg & VOL_SWEEP_MASK; self.volume_counter = if self.volume_modulo == 0 {None} else {Some(0)}; let freq_modulo_shift = (self.poly_counter_reg & FREQ_SHIFT_MASK) >> 4; self.freq_modulo = match self.poly_counter_reg & FREQ_DIVISOR_MASK { 0 => 8, x => (x as u32) * 16, } << freq_modulo_shift; self.freq_counter = 0; self.length_counter = MAX_LEN; self.length_modulo = self.length_reg & LEN_MASK; self.lfsr_counter = 0xFFFF; self.enabled = true; } f
}
n lfsr_step(&mut self) { const LFSR_MASK: u16 = 0x3FFF; const LFSR_7BIT_MASK: u16 = 0xFFBF; let low_bit = self.lfsr_counter & 1; self.lfsr_counter >>= 1; let xor_bit = (self.lfsr_counter & 1) ^ low_bit; self.lfsr_counter = (self.lfsr_counter & LFSR_MASK) | (xor_bit << 14); if test_bit!(self.poly_counter_reg, 3) { self.lfsr_counter = (self.lfsr_counter & LFSR_7BIT_MASK) | (xor_bit << 6); } }
function_block-function_prefixed
[ { "content": "// Convert from 4-bit signed samples to 32-bit floating point.\n\npub fn i4_to_f32(amplitude: u8) -> f32 {\n\n const MAX_AMP: f32 = 7.5;\n\n\n\n ((amplitude as f32) - MAX_AMP) / MAX_AMP\n\n}", "file_path": "src/audio/channels/mod.rs", "rank": 0, "score": 189128.31516370102 }, ...
Rust
src/app/procedure.rs
luxrck/sic
6dd2bda9ff7d19387db82e271abb614e1d9dab9d
use std::error::Error; use std::io::Read; use std::path::Path; use clap::ArgMatches; use sic_core::image; use sic_image_engine::engine::ImageEngine; use sic_io::conversion::AutomaticColorTypeAdjustment; use sic_io::format::{ DetermineEncodingFormat, EncodingFormatByIdentifier, EncodingFormatByMethod, JPEGQuality, }; use sic_io::load::{load_image, ImportConfig}; use sic_io::save::{export, ExportMethod, ExportSettings}; use crate::app::cli::arg_names::{ARG_INPUT, ARG_INPUT_FILE}; use crate::app::config::Config; use crate::app::license::PrintTextFor; const NO_INPUT_PATH_MSG: &str = "Input path was expected but could not be found."; pub fn run(matches: &ArgMatches, options: &Config) -> Result<(), String> { if options.output.is_none() { eprintln!( "The default output format is BMP. Use --output-format <FORMAT> to specify \ a different output format." ); } let mut reader = mk_reader(matches)?; let img = load_image( &mut reader, &ImportConfig { selected_frame: options.selected_frame, }, )?; let mut image_engine = ImageEngine::new(img); let buffer = image_engine .ignite(&options.image_operations_program) .map_err(|err| err.to_string())?; let export_method = determine_export_method(options.output.as_ref()).map_err(|err| err.to_string())?; let encoding_format_determiner = DetermineEncodingFormat { pnm_sample_encoding: if options.encoding_settings.pnm_use_ascii_format { Some(image::pnm::SampleEncoding::Ascii) } else { Some(image::pnm::SampleEncoding::Binary) }, jpeg_quality: { let quality = JPEGQuality::try_from(options.encoding_settings.jpeg_quality) .map_err(|err| err.to_string()); Some(quality?) }, }; let encoding_format = match &options.forced_output_format { Some(format) => encoding_format_determiner.by_identifier(format), None => encoding_format_determiner.by_method(&export_method), } .map_err(|err| err.to_string())?; export( buffer, export_method, encoding_format, ExportSettings { adjust_color_type: AutomaticColorTypeAdjustment::default(), }, ) } fn mk_reader(matches: &ArgMatches) -> Result<Box<dyn Read>, String> { fn with_file_reader(matches: &ArgMatches, value_of: &str) -> Result<Box<dyn Read>, String> { Ok(sic_io::load::file_reader( matches .value_of(value_of) .ok_or_else(|| NO_INPUT_PATH_MSG.to_string())?, )?) }; let reader = if matches.is_present(ARG_INPUT) { with_file_reader(matches, ARG_INPUT)? } else if matches.is_present(ARG_INPUT_FILE) { with_file_reader(matches, ARG_INPUT_FILE)? } else { if atty::is(atty::Stream::Stdin) { return Err( "An input image should be given by providing a path using the input argument or by \ piping an image to the stdin.".to_string(), ); } sic_io::load::stdin_reader()? }; Ok(reader) } fn determine_export_method<P: AsRef<Path>>( output_path: Option<P>, ) -> Result<ExportMethod<P>, Box<dyn Error>> { let method = if output_path.is_none() { ExportMethod::StdoutBytes } else { let path = output_path .ok_or_else(|| "The export method 'file' requires an output file path.".to_string()); ExportMethod::File(path?) }; Ok(method) } pub fn run_display_licenses(config: &Config) -> Result<(), String> { config .show_license_text_of .ok_or_else(|| "Unable to display license texts".to_string()) .and_then(|license_text| license_text.print()) }
use std::error::Error; use std::io::Read; use std::path::Path; use clap::ArgMatches; use sic_core::image; use sic_image_engine::engine::ImageEngine; use sic_io::conversion::AutomaticColorTypeAdjustment; use sic_io::format::{ DetermineEncodingFormat, EncodingFormatByIdentifier, EncodingFormatByMethod, JPEGQuality, }; use sic_io::load::{load_image, ImportConfig}; use sic_io::save::{export, ExportMethod, ExportSettings}; use crate::app::cli::arg_names::{ARG_INPUT, ARG_INPUT_FILE}; use crate::app::config::Config; use crate::app::license::PrintTextFor; const NO_INPUT_PATH_MSG: &str = "Input path was expected but could not be found."; pub fn run(matches: &ArgMatches, options: &Config) -> Result<(), String> { if options.output.is_none() { eprintln!( "The default output format is BMP. Use --output-format <FORMAT> to specify \ a different output format." ); } let mut reader = mk_reader(matches)?; let img = load_image( &mut reader, &ImportConfig { selected_frame: options.selected_frame, }, )?; let mut image_engine = ImageEngine::new(img); let buffer = image_engine .ignite(&options.image_operations_program) .map_err(|err| err.to_string())?; let export_method = determine_export_method(options.output.as_ref()).map_err(|err| err.to_string())?; let encoding_format_determiner = DetermineEncodingFormat { pnm_sample_encoding: if options.encoding_settings.pnm_use_ascii_format { Some(image::pnm::SampleEncoding::Ascii) } else { Some(image::pnm::SampleEncoding::Binary) }, jpeg_quality: { let quality = JPEGQuality::try_from(options.encoding_settings.jpeg_quality) .map_err(|err| err.to_string()); Some(quality?) }, }; let encoding_format = match &options.forced_output_format { Some(format) => encoding_format_determiner.by_identifier(format), None => encoding_format_determiner.by_method(&export_method), } .map_err(|err| err.to_string())?; export( buffer, export_method, encoding_format, ExportSettings { adjust_color_type: AutomaticColorTypeAdjustment::default(), }, ) } fn mk_reader(matches: &ArgMatches) -> Result<Box<dyn Read>, String> { fn with_file_reader(matches: &ArgMatches, value_of: &str) -> Result<Box<dyn Read>, String> { Ok(sic_io::load::file_reader( matches .value_of(value_of) .ok_or_else(|| NO_INPUT_PATH_MSG.to_string())?, )?) }; let reader = if matches.is_present(ARG_INPUT) { with_file_reader(matches, ARG_INPUT)? } else if matches.is_present(ARG_INPUT_FILE) { with_file_reader(matches, ARG_INPUT_FILE)? } else { if atty::is(atty::Stream::Stdin) { return Err( "An input image should be given by providing a path using the input argument or by \ piping an image to the stdin.".to_string(), ); } sic_io::load::stdin_reader()? }; Ok(reader) } fn determine_export_method<P: AsRef<Path>>( output_path: Option<P>, ) -> Result<ExportMethod<P>, Box<dyn Error>> { let method = if output_path.is_none() { ExportMethod::StdoutBytes } else { let path = output_path .ok_or_else(|| "The export method 'file' requires an output file path.".to_string()); ExportMethod::File(path?) }; Ok(method) }
pub fn run_display_licenses(config: &Config) -> Result<(), String> { config .show_license_text_of .ok_or_else(|| "Unable to display license texts".to_string()) .and_then(|license_text| license_text.print()) }
function_block-full_function
[ { "content": "// Here any argument should not panic when invalid.\n\n// Previously, it was allowed to panic within Config, but this is no longer the case.\n\npub fn build_app_config<'a>(matches: &'a ArgMatches) -> Result<Config<'a>, String> {\n\n let mut builder = ConfigBuilder::new();\n\n\n\n // organisa...
Rust
splashsurf/src/io/vtk_format.rs
rezural/splashsurf
a5e5497e08d32bce92d5f5016ae8a33550f5598d
use anyhow::{anyhow, Context}; use splashsurf_lib::mesh::{MeshWithData, TriMesh3d}; use splashsurf_lib::nalgebra::Vector3; use splashsurf_lib::vtkio; use splashsurf_lib::vtkio::model::{ Attributes, CellType, Cells, UnstructuredGridPiece, VertexNumbers, }; use splashsurf_lib::Real; use std::fs::create_dir_all; use std::path::Path; use vtkio::model::{ByteOrder, DataSet, Version, Vtk}; use vtkio::IOBuffer; pub fn particles_from_vtk<R: Real, P: AsRef<Path>>( vtk_file: P, ) -> Result<Vec<Vector3<R>>, anyhow::Error> { let particle_dataset = read_vtk(vtk_file)?; particles_from_dataset(particle_dataset) } pub fn particles_to_vtk<R: Real, P: AsRef<Path>>( particles: &[Vector3<R>], vtk_file: P, ) -> Result<(), anyhow::Error> { write_vtk( UnstructuredGridPiece::from(Particles(particles)), vtk_file, "particles", ) } pub fn surface_mesh_from_vtk<R: Real, P: AsRef<Path>>( vtk_file: P, ) -> Result<MeshWithData<R, TriMesh3d<R>>, anyhow::Error> { let mesh_dataset = read_vtk(vtk_file)?; surface_mesh_from_dataset(mesh_dataset) } pub fn write_vtk<P: AsRef<Path>>( data: impl Into<DataSet>, filename: P, title: &str, ) -> Result<(), anyhow::Error> { let vtk_file = Vtk { version: Version::new((4, 1)), title: title.to_string(), file_path: None, byte_order: ByteOrder::BigEndian, data: data.into(), }; let filename = filename.as_ref(); if let Some(dir) = filename.parent() { create_dir_all(dir).context("Failed to create parent directory of output file")?; } vtk_file .export_be(filename) .context("Error while writing VTK output to file") } pub fn read_vtk<P: AsRef<Path>>(filename: P) -> Result<DataSet, vtkio::Error> { let filename = filename.as_ref(); Vtk::import_legacy_be(filename).map(|vtk| vtk.data) } pub fn particles_from_coords<RealOut: Real, RealIn: Real>( coords: &Vec<RealIn>, ) -> Result<Vec<Vector3<RealOut>>, anyhow::Error> { if coords.len() % 3 != 0 { anyhow!("The number of values in the particle data point buffer is not divisible by 3"); } let num_points = coords.len() / 3; let mut positions = Vec::with_capacity(num_points); for i in 0..num_points { positions.push(Vector3::new( RealOut::from_f64(coords[3 * i + 0].to_f64().unwrap()).unwrap(), RealOut::from_f64(coords[3 * i + 1].to_f64().unwrap()).unwrap(), RealOut::from_f64(coords[3 * i + 2].to_f64().unwrap()).unwrap(), )) } Ok(positions) } pub fn particles_from_dataset<R: Real>(dataset: DataSet) -> Result<Vec<Vector3<R>>, anyhow::Error> { if let DataSet::UnstructuredGrid { pieces, .. } = dataset { if let Some(piece) = pieces.into_iter().next() { let points = piece .into_loaded_piece_data(None) .context("Failed to load unstructured grid piece")? .points; match points { IOBuffer::F64(coords) => particles_from_coords(&coords), IOBuffer::F32(coords) => particles_from_coords(&coords), _ => Err(anyhow!( "Point coordinate IOBuffer does not contain f32 or f64 values" )), } } else { Err(anyhow!( "Loaded dataset does not contain an unstructured grid piece" )) } } else { Err(anyhow!( "Loaded dataset does not contain an unstructured grid" )) } } pub fn surface_mesh_from_dataset<R: Real>( dataset: DataSet, ) -> Result<MeshWithData<R, TriMesh3d<R>>, anyhow::Error> { if let DataSet::UnstructuredGrid { pieces, .. } = dataset { if let Some(piece) = pieces.into_iter().next() { let piece = piece .into_loaded_piece_data(None) .context("Failed to load unstructured grid piece")?; let vertices = match piece.points { IOBuffer::F64(coords) => particles_from_coords(&coords), IOBuffer::F32(coords) => particles_from_coords(&coords), _ => Err(anyhow!( "Point coordinate IOBuffer does not contain f32 or f64 values" )), }?; let triangles = { let (num_cells, cell_verts) = piece.cells.cell_verts.into_legacy(); if cell_verts.len() % 4 == 0 { let mut cells = Vec::with_capacity(num_cells as usize); cell_verts.chunks_exact(4).try_for_each(|cell| { if cell[0] == 3 { cells.push([cell[1] as usize, cell[2] as usize, cell[3] as usize]); Ok(()) } else { Err(anyhow!("Invalid number of vertex indices per cell")) } })?; cells } else { return Err(anyhow!("Invalid number of vertex indices per cell")); } }; Ok(MeshWithData::new(TriMesh3d { vertices, triangles, })) } else { Err(anyhow!( "Loaded dataset does not contain an unstructured grid piece" )) } } else { Err(anyhow!( "Loaded dataset does not contain an unstructured grid" )) } } struct Particles<'a, R: Real>(&'a [Vector3<R>]); impl<'a, R> From<Particles<'a, R>> for UnstructuredGridPiece where R: Real, { fn from(particles: Particles<'a, R>) -> Self { let particles = particles.0; let points = { let mut points: Vec<R> = Vec::with_capacity(particles.len() * 3); for p in particles.iter() { points.extend(p.as_slice()); } points }; let vertices = { let mut vertices = Vec::with_capacity(particles.len() * (1 + 1)); for i in 0..particles.len() { vertices.push(1); vertices.push(i as u32); } vertices }; let cell_types = vec![CellType::Vertex; particles.len()]; UnstructuredGridPiece { points: points.into(), cells: Cells { cell_verts: VertexNumbers::Legacy { num_cells: cell_types.len() as u32, vertices, }, types: cell_types, }, data: Attributes::new(), } } }
use anyhow::{anyhow, Context}; use splashsurf_lib::mesh::{MeshWithData, TriMesh3d}; use splashsurf_lib::nalgebra::Vector3; use splashsurf_lib::vtkio; use splashsurf_lib::vtkio::model::{ Attributes, CellType, Cells, UnstructuredGridPiece, VertexNumbers, }; use splashsurf_lib::Real; use std::fs::create_dir_all; use std::path::Path; use vtkio::model::{ByteOrder, DataSet, Version, Vtk}; use vtkio::IOBuffer; pub fn particles_from_vtk<R: Real, P: AsRef<Path>>( vtk_file: P, ) -> Result<Vec<Vector3<R>>, anyhow::Error> { let particle_dataset = read_vtk(vtk_file)?; particles_from_dataset(particle_dataset) } pub fn particles_to_vtk<R: Real, P: AsRef<Path>>( particles: &[Vector3<R>], vtk_file: P, ) -> Result<(), anyhow::Error> { write_vtk( UnstructuredGridPiece::from(Particles(particles)), vtk_file, "particles", ) } pub fn surface_mesh_from_vtk<R: Real, P: AsRef<Path>>( vtk_file: P, ) -> Result<MeshWithData<R, TriMesh3d<R>>, anyhow::Error> { let mesh_dataset = read_vtk(vtk_file)?; surface_mesh_from_dataset(mesh_dataset) } pub fn write_vtk<P: AsRef<Path>>( data: impl Into<DataSet>, filename: P, title: &str, ) -> Result<(), anyhow::Error> { let vtk_file = Vtk { version: Version::new((4, 1)), title: title.to_string(), file_path: None, byte_order: ByteOrder::BigEndian, data: data.into(), }; let filename = filename.as_ref(); if let Some(dir) = filename.parent() { create_dir_all(dir).context("Failed to create parent directory of output file")?; } vtk_file .export_be(filename) .context("Error while writing VTK output to file") } pub fn read_vtk<P: AsRef<Path>>(filename: P) -> Result<DataSet, vtkio::Error> { let filename = filename.as_ref(); Vtk::import_legacy_be(filename).map(|vtk| vtk.data) } pub fn particles_from_coords<RealOut: Real, RealIn: Real>( coords: &Vec<RealIn>, ) -> Result<Vec<Vector3<RealOut>>, anyhow::Error> { if coords.len() % 3 != 0 { anyhow!("The number of values in the particle data point buffer is not divisible by 3"); } let num_points = coords.len() / 3; let mut positions = Vec::with_capacity(num_points); for i in 0..num_points { positions.push(Vector3::new( RealOut::from_f64(coords[3 * i + 0].to_f64().unwrap()).unwrap(), RealOut::from_f64(coords[3 * i + 1].to_f64().unwrap()).unwrap(), RealOut::from_f64(coords[3 * i + 2].to_f64().unwrap()).unwrap(), )) } Ok(positions) } pub fn particles_from_dataset<R: Real>(dataset: DataSet) -> Result<Vec<Vector3<R>>, anyhow::Error> { if let DataSet::UnstructuredGrid { pieces, .. } = dataset { if let Some(piece) = pieces.into_iter().next() { let points = piece .into_loaded_piece_data(None) .context("Failed to load unstructured grid piece")? .points; match points { IOBuffer::F64(coords) => particles_from_coords(&coords), IOBuffer::F32(coords) => particles_from_coords(&coords), _ => Err(anyhow!( "Point coordinate IOBuffer does not contain f32 or f64 values" )), } } else { Err(anyhow!( "Loaded dataset does not contain an unstructured grid piece" )) } } else { Err(anyhow!( "Loaded dataset does not contain an unstructured grid" )) } } pub fn surface_mesh_from_dataset<R: Real>( dataset: DataSet, ) -> Result<MeshWithData<R, TriMesh3d<R>>, anyhow::Error> { if let DataSet::UnstructuredGrid { pieces, .. } = dataset { if let Some(piece) = pieces.into_iter().next() { let piece = piece .into_loaded_piece_data(None) .context("Failed to load unstructured grid piece")?; let vertices = match piece.points { IOBuffer::F64(coords) => particles_from_coords(&coords), IOBuffer::F32(coords) => particles_from_coords(&coords), _ => Err(anyhow!( "Point coordinate IOBuffer does not contain f32 or f64 values" )), }?; let triangles = { let (num_cells, cell_verts) = piece.cells.cell_verts.into_legacy(); if cell_verts.len() % 4 == 0 { let mut cells = Vec::with_capacity(num_cells as usiz
struct Particles<'a, R: Real>(&'a [Vector3<R>]); impl<'a, R> From<Particles<'a, R>> for UnstructuredGridPiece where R: Real, { fn from(particles: Particles<'a, R>) -> Self { let particles = particles.0; let points = { let mut points: Vec<R> = Vec::with_capacity(particles.len() * 3); for p in particles.iter() { points.extend(p.as_slice()); } points }; let vertices = { let mut vertices = Vec::with_capacity(particles.len() * (1 + 1)); for i in 0..particles.len() { vertices.push(1); vertices.push(i as u32); } vertices }; let cell_types = vec![CellType::Vertex; particles.len()]; UnstructuredGridPiece { points: points.into(), cells: Cells { cell_verts: VertexNumbers::Legacy { num_cells: cell_types.len() as u32, vertices, }, types: cell_types, }, data: Attributes::new(), } } }
e); cell_verts.chunks_exact(4).try_for_each(|cell| { if cell[0] == 3 { cells.push([cell[1] as usize, cell[2] as usize, cell[3] as usize]); Ok(()) } else { Err(anyhow!("Invalid number of vertex indices per cell")) } })?; cells } else { return Err(anyhow!("Invalid number of vertex indices per cell")); } }; Ok(MeshWithData::new(TriMesh3d { vertices, triangles, })) } else { Err(anyhow!( "Loaded dataset does not contain an unstructured grid piece" )) } } else { Err(anyhow!( "Loaded dataset does not contain an unstructured grid" )) } }
function_block-function_prefixed
[ { "content": "#[allow(dead_code)]\n\npub fn to_binary_f32<R: Real, P: AsRef<Path>>(file: P, values: &[R]) -> Result<(), anyhow::Error> {\n\n let file = file.as_ref();\n\n let file = File::create(file).context(\"Unable to create binary file\")?;\n\n let mut writer = BufWriter::new(file);\n\n\n\n for ...
Rust
tests/support/mod.rs
aanari/redis-rs
eb367b927cb65cd2da302bd0534ce330d72a48ef
#![allow(dead_code)] use futures; use net2; use rand; use redis; use std::env; use std::fs; use std::io::{self, Write}; use std::process; use std::thread::sleep; use std::time::Duration; use std::path::PathBuf; use self::futures::Future; use redis::Value; pub fn current_thread_runtime() -> tokio::runtime::Runtime { let mut builder = tokio::runtime::Builder::new(); #[cfg(feature = "aio")] builder.enable_io(); builder.basic_scheduler().build().unwrap() } pub fn block_on_all<F>(f: F) -> F::Output where F: Future, { current_thread_runtime().block_on(f) } #[cfg(feature = "async-std-comp")] pub fn block_on_all_using_async_std<F>(f: F) -> F::Output where F: Future, { async_std::task::block_on(f) } #[cfg(feature = "cluster")] mod cluster; #[cfg(feature = "cluster")] pub use self::cluster::*; #[derive(PartialEq)] enum ServerType { Tcp { tls: bool }, Unix, } pub struct RedisServer { pub processes: Vec<process::Child>, addr: redis::ConnectionAddr, } impl ServerType { fn get_intended() -> ServerType { match env::var("REDISRS_SERVER_TYPE") .ok() .as_ref() .map(|x| &x[..]) { Some("tcp") => ServerType::Tcp { tls: false }, Some("tcp+tls") => ServerType::Tcp { tls: true }, Some("unix") => ServerType::Unix, val => { panic!("Unknown server type {:?}", val); } } } } impl RedisServer { pub fn new() -> RedisServer { let server_type = ServerType::get_intended(); match server_type { ServerType::Tcp { tls } => { let redis_listener = net2::TcpBuilder::new_v4() .unwrap() .reuse_address(true) .unwrap() .bind("127.0.0.1:0") .unwrap() .listen(1) .unwrap(); let redis_port = redis_listener.local_addr().unwrap().port(); if tls { process::Command::new("openssl") .args(&[ "req", "-nodes", "-new", "-x509", "-keyout", &format!("/tmp/redis-rs-test-{}.pem", redis_port), "-out", &format!("/tmp/redis-rs-test-{}.crt", redis_port), "-subj", "/C=XX/ST=crates/L=redis-rs/O=testing/CN=localhost", ]) .stdout(process::Stdio::null()) .stderr(process::Stdio::null()) .spawn() .expect("failed to spawn openssl") .wait() .expect("failed to create self-signed TLS certificate"); let stunnel_listener = net2::TcpBuilder::new_v4() .unwrap() .reuse_address(true) .unwrap() .bind("127.0.0.1:0") .unwrap() .listen(1) .unwrap(); let stunnel_port = stunnel_listener.local_addr().unwrap().port(); let stunnel_config_path = format!("/tmp/redis-rs-stunnel-{}.conf", redis_port); let mut stunnel_config_file = fs::File::create(&stunnel_config_path).unwrap(); stunnel_config_file .write_all( format!( r#" cert = /tmp/redis-rs-test-{redis_port}.crt key = /tmp/redis-rs-test-{redis_port}.pem verify = 0 foreground = yes [redis] accept = 127.0.0.1:{stunnel_port} connect = 127.0.0.1:{redis_port} "#, stunnel_port = stunnel_port, redis_port = redis_port ) .as_bytes(), ) .expect("could not write stunnel config file"); let addr = redis::ConnectionAddr::Tcp("127.0.0.1".to_string(), redis_port); let mut server = RedisServer::new_with_addr(addr, |cmd| { let stunnel = process::Command::new("stunnel") .arg(&stunnel_config_path) .stdout(process::Stdio::null()) .stderr(process::Stdio::null()) .spawn() .expect("could not start stunnel"); vec![stunnel, cmd.spawn().unwrap()] }); server.addr = redis::ConnectionAddr::TcpTls { host: "127.0.0.1".to_string(), port: stunnel_port, insecure: true, }; server } else { let addr = redis::ConnectionAddr::Tcp("127.0.0.1".to_string(), redis_port); RedisServer::new_with_addr(addr, |cmd| vec![cmd.spawn().unwrap()]) } } ServerType::Unix => { let (a, b) = rand::random::<(u64, u64)>(); let path = format!("/tmp/redis-rs-test-{}-{}.sock", a, b); let addr = redis::ConnectionAddr::Unix(PathBuf::from(&path)); RedisServer::new_with_addr(addr, |cmd| vec![cmd.spawn().unwrap()]) } } } pub fn new_with_addr<F: FnOnce(&mut process::Command) -> Vec<process::Child>>( addr: redis::ConnectionAddr, spawner: F, ) -> RedisServer { let mut cmd = process::Command::new("redis-server"); cmd.stdout(process::Stdio::null()) .stderr(process::Stdio::null()); match addr { redis::ConnectionAddr::Tcp(ref bind, server_port) => { cmd.arg("--port") .arg(server_port.to_string()) .arg("--bind") .arg(bind); } redis::ConnectionAddr::TcpTls { ref host, port, .. } => { cmd.arg("--port") .arg(port.to_string()) .arg("--bind") .arg(host); } redis::ConnectionAddr::Unix(ref path) => { cmd.arg("--port").arg("0").arg("--unixsocket").arg(&path); } }; RedisServer { processes: spawner(&mut cmd), addr, } } pub fn wait(&mut self) { for p in self.processes.iter_mut() { p.wait().unwrap(); } } pub fn get_client_addr(&self) -> &redis::ConnectionAddr { &self.addr } pub fn stop(&mut self) { for p in self.processes.iter_mut() { let _ = p.kill(); let _ = p.wait(); } if let redis::ConnectionAddr::Unix(ref path) = *self.get_client_addr() { fs::remove_file(&path).ok(); } } } impl Drop for RedisServer { fn drop(&mut self) { self.stop() } } pub struct TestContext { pub server: RedisServer, pub client: redis::Client, } impl TestContext { pub fn new() -> TestContext { let server = RedisServer::new(); let client = redis::Client::open(redis::ConnectionInfo { addr: Box::new(server.get_client_addr().clone()), db: 0, passwd: None, }) .unwrap(); let mut con; let millisecond = Duration::from_millis(1); loop { match client.get_connection() { Err(err) => { if err.is_connection_refusal() { sleep(millisecond); } else { panic!("Could not connect: {}", err); } } Ok(x) => { con = x; break; } } } redis::cmd("FLUSHDB").execute(&mut con); TestContext { server, client } } pub fn connection(&self) -> redis::Connection { self.client.get_connection().unwrap() } #[cfg(feature = "aio")] pub async fn async_connection(&self) -> redis::RedisResult<redis::aio::Connection> { self.client.get_async_connection().await } #[cfg(feature = "async-std-comp")] pub async fn async_connection_async_std(&self) -> redis::RedisResult<redis::aio::Connection> { self.client.get_async_std_connection().await } pub fn stop_server(&mut self) { self.server.stop(); } #[cfg(feature = "tokio-rt-core")] pub fn multiplexed_async_connection( &self, ) -> impl Future<Output = redis::RedisResult<redis::aio::MultiplexedConnection>> { self.multiplexed_async_connection_tokio() } #[cfg(feature = "tokio-rt-core")] pub fn multiplexed_async_connection_tokio( &self, ) -> impl Future<Output = redis::RedisResult<redis::aio::MultiplexedConnection>> { let client = self.client.clone(); async move { client.get_multiplexed_tokio_connection().await } } #[cfg(feature = "async-std-comp")] pub fn multiplexed_async_connection_async_std( &self, ) -> impl Future<Output = redis::RedisResult<redis::aio::MultiplexedConnection>> { let client = self.client.clone(); async move { client.get_multiplexed_async_std_connection().await } } } pub fn encode_value<W>(value: &Value, writer: &mut W) -> io::Result<()> where W: io::Write, { #![allow(clippy::write_with_newline)] match *value { Value::Nil => write!(writer, "$-1\r\n"), Value::Int(val) => write!(writer, ":{}\r\n", val), Value::Data(ref val) => { write!(writer, "${}\r\n", val.len())?; writer.write_all(val)?; writer.write_all(b"\r\n") } Value::Bulk(ref values) => { write!(writer, "*{}\r\n", values.len())?; for val in values.iter() { encode_value(val, writer)?; } Ok(()) } Value::Okay => write!(writer, "+OK\r\n"), Value::Status(ref s) => write!(writer, "+{}\r\n", s), } }
#![allow(dead_code)] use futures; use net2; use rand; use redis; use std::env; use std::fs; use std::io::{self, Write}; use std::process; use std::thread::sleep; use std::time::Duration; use std::path::PathBuf; use self::futures::Future; use redis::Value; pub fn current_thread_runtime() -> tokio::runtime::Runtime { let mut builder = tokio::runtime::Builder::new(); #[cfg(feature = "aio")] builder.enable_io(); builder.basic_scheduler().build().unwrap() } pub fn block_on_all<F>(f: F) -> F::Output where F: Future, { current_thread_runtime().block_on(f) } #[cfg(feature = "async-std-comp")] pub fn block_on_all_using_async_std<F>(f: F) -> F::Output where F: Future, { async_std::task::block_on(f) } #[cfg(feature = "cluster")] mod cluster; #[cfg(feature = "cluster")] pub use self::cluster::*; #[derive(PartialEq)] enum ServerType { Tcp { tls: bool }, Unix, } pub struct RedisServer { pub processes: Vec<process::Child>, addr: redis::ConnectionAddr, } impl ServerType {
} impl RedisServer { pub fn new() -> RedisServer { let server_type = ServerType::get_intended(); match server_type { ServerType::Tcp { tls } => { let redis_listener = net2::TcpBuilder::new_v4() .unwrap() .reuse_address(true) .unwrap() .bind("127.0.0.1:0") .unwrap() .listen(1) .unwrap(); let redis_port = redis_listener.local_addr().unwrap().port(); if tls { process::Command::new("openssl") .args(&[ "req", "-nodes", "-new", "-x509", "-keyout", &format!("/tmp/redis-rs-test-{}.pem", redis_port), "-out", &format!("/tmp/redis-rs-test-{}.crt", redis_port), "-subj", "/C=XX/ST=crates/L=redis-rs/O=testing/CN=localhost", ]) .stdout(process::Stdio::null()) .stderr(process::Stdio::null()) .spawn() .expect("failed to spawn openssl") .wait() .expect("failed to create self-signed TLS certificate"); let stunnel_listener = net2::TcpBuilder::new_v4() .unwrap() .reuse_address(true) .unwrap() .bind("127.0.0.1:0") .unwrap() .listen(1) .unwrap(); let stunnel_port = stunnel_listener.local_addr().unwrap().port(); let stunnel_config_path = format!("/tmp/redis-rs-stunnel-{}.conf", redis_port); let mut stunnel_config_file = fs::File::create(&stunnel_config_path).unwrap(); stunnel_config_file .write_all( format!( r#" cert = /tmp/redis-rs-test-{redis_port}.crt key = /tmp/redis-rs-test-{redis_port}.pem verify = 0 foreground = yes [redis] accept = 127.0.0.1:{stunnel_port} connect = 127.0.0.1:{redis_port} "#, stunnel_port = stunnel_port, redis_port = redis_port ) .as_bytes(), ) .expect("could not write stunnel config file"); let addr = redis::ConnectionAddr::Tcp("127.0.0.1".to_string(), redis_port); let mut server = RedisServer::new_with_addr(addr, |cmd| { let stunnel = process::Command::new("stunnel") .arg(&stunnel_config_path) .stdout(process::Stdio::null()) .stderr(process::Stdio::null()) .spawn() .expect("could not start stunnel"); vec![stunnel, cmd.spawn().unwrap()] }); server.addr = redis::ConnectionAddr::TcpTls { host: "127.0.0.1".to_string(), port: stunnel_port, insecure: true, }; server } else { let addr = redis::ConnectionAddr::Tcp("127.0.0.1".to_string(), redis_port); RedisServer::new_with_addr(addr, |cmd| vec![cmd.spawn().unwrap()]) } } ServerType::Unix => { let (a, b) = rand::random::<(u64, u64)>(); let path = format!("/tmp/redis-rs-test-{}-{}.sock", a, b); let addr = redis::ConnectionAddr::Unix(PathBuf::from(&path)); RedisServer::new_with_addr(addr, |cmd| vec![cmd.spawn().unwrap()]) } } } pub fn new_with_addr<F: FnOnce(&mut process::Command) -> Vec<process::Child>>( addr: redis::ConnectionAddr, spawner: F, ) -> RedisServer { let mut cmd = process::Command::new("redis-server"); cmd.stdout(process::Stdio::null()) .stderr(process::Stdio::null()); match addr { redis::ConnectionAddr::Tcp(ref bind, server_port) => { cmd.arg("--port") .arg(server_port.to_string()) .arg("--bind") .arg(bind); } redis::ConnectionAddr::TcpTls { ref host, port, .. } => { cmd.arg("--port") .arg(port.to_string()) .arg("--bind") .arg(host); } redis::ConnectionAddr::Unix(ref path) => { cmd.arg("--port").arg("0").arg("--unixsocket").arg(&path); } }; RedisServer { processes: spawner(&mut cmd), addr, } } pub fn wait(&mut self) { for p in self.processes.iter_mut() { p.wait().unwrap(); } } pub fn get_client_addr(&self) -> &redis::ConnectionAddr { &self.addr } pub fn stop(&mut self) { for p in self.processes.iter_mut() { let _ = p.kill(); let _ = p.wait(); } if let redis::ConnectionAddr::Unix(ref path) = *self.get_client_addr() { fs::remove_file(&path).ok(); } } } impl Drop for RedisServer { fn drop(&mut self) { self.stop() } } pub struct TestContext { pub server: RedisServer, pub client: redis::Client, } impl TestContext { pub fn new() -> TestContext { let server = RedisServer::new(); let client = redis::Client::open(redis::ConnectionInfo { addr: Box::new(server.get_client_addr().clone()), db: 0, passwd: None, }) .unwrap(); let mut con; let millisecond = Duration::from_millis(1); loop { match client.get_connection() { Err(err) => { if err.is_connection_refusal() { sleep(millisecond); } else { panic!("Could not connect: {}", err); } } Ok(x) => { con = x; break; } } } redis::cmd("FLUSHDB").execute(&mut con); TestContext { server, client } } pub fn connection(&self) -> redis::Connection { self.client.get_connection().unwrap() } #[cfg(feature = "aio")] pub async fn async_connection(&self) -> redis::RedisResult<redis::aio::Connection> { self.client.get_async_connection().await } #[cfg(feature = "async-std-comp")] pub async fn async_connection_async_std(&self) -> redis::RedisResult<redis::aio::Connection> { self.client.get_async_std_connection().await } pub fn stop_server(&mut self) { self.server.stop(); } #[cfg(feature = "tokio-rt-core")] pub fn multiplexed_async_connection( &self, ) -> impl Future<Output = redis::RedisResult<redis::aio::MultiplexedConnection>> { self.multiplexed_async_connection_tokio() } #[cfg(feature = "tokio-rt-core")] pub fn multiplexed_async_connection_tokio( &self, ) -> impl Future<Output = redis::RedisResult<redis::aio::MultiplexedConnection>> { let client = self.client.clone(); async move { client.get_multiplexed_tokio_connection().await } } #[cfg(feature = "async-std-comp")] pub fn multiplexed_async_connection_async_std( &self, ) -> impl Future<Output = redis::RedisResult<redis::aio::MultiplexedConnection>> { let client = self.client.clone(); async move { client.get_multiplexed_async_std_connection().await } } } pub fn encode_value<W>(value: &Value, writer: &mut W) -> io::Result<()> where W: io::Write, { #![allow(clippy::write_with_newline)] match *value { Value::Nil => write!(writer, "$-1\r\n"), Value::Int(val) => write!(writer, ":{}\r\n", val), Value::Data(ref val) => { write!(writer, "${}\r\n", val.len())?; writer.write_all(val)?; writer.write_all(b"\r\n") } Value::Bulk(ref values) => { write!(writer, "*{}\r\n", values.len())?; for val in values.iter() { encode_value(val, writer)?; } Ok(()) } Value::Okay => write!(writer, "+OK\r\n"), Value::Status(ref s) => write!(writer, "+{}\r\n", s), } }
fn get_intended() -> ServerType { match env::var("REDISRS_SERVER_TYPE") .ok() .as_ref() .map(|x| &x[..]) { Some("tcp") => ServerType::Tcp { tls: false }, Some("tcp+tls") => ServerType::Tcp { tls: true }, Some("unix") => ServerType::Unix, val => { panic!("Unknown server type {:?}", val); } } }
function_block-full_function
[ { "content": "fn check_connection(conn: &mut Connection) -> bool {\n\n let mut cmd = Cmd::new();\n\n cmd.arg(\"PING\");\n\n cmd.query::<String>(conn).is_ok()\n\n}\n\n\n", "file_path": "src/cluster.rs", "rank": 2, "score": 187254.723174657 }, { "content": "fn write_command<'a, I>(cmd...
Rust
zscene/examples/action.rs
zouharvi/zemeroth
455c8c82991b4bfc40fddf68f66f59d67d1641e1
use std::time::Duration; use mq::{ camera::{set_camera, Camera2D}, color::{Color, BLACK}, math::{Rect, Vec2}, text, texture::{self, Texture2D}, time, window, }; use zscene::{self, action, Action, Boxed, Layer, Scene, Sprite}; #[derive(Debug)] pub enum Err { File(mq::file::FileError), Font(mq::text::FontError), } impl From<mq::file::FileError> for Err { fn from(err: mq::file::FileError) -> Self { Err::File(err) } } impl From<mq::text::FontError> for Err { fn from(err: mq::text::FontError) -> Self { Err::Font(err) } } #[derive(Debug, Clone, Default)] pub struct Layers { pub bg: Layer, pub fg: Layer, } impl Layers { fn sorted(self) -> Vec<Layer> { vec![self.bg, self.fg] } } struct Assets { font: text::Font, texture: Texture2D, } impl Assets { async fn load() -> Result<Self, Err> { let font = text::load_ttf_font("zscene/assets/Karla-Regular.ttf").await?; let texture = texture::load_texture("zscene/assets/fire.png").await?; Ok(Self { font, texture }) } } struct State { assets: Assets, scene: Scene, layers: Layers, } impl State { fn new(assets: Assets) -> Self { let layers = Layers::default(); let scene = Scene::new(layers.clone().sorted()); update_aspect_ratio(); Self { assets, scene, layers, } } fn action_demo_move(&self) -> Box<dyn Action> { let mut sprite = Sprite::from_texture(self.assets.texture, 0.5); sprite.set_pos(Vec2::new(0.0, -1.0)); let delta = Vec2::new(0.0, 1.5); let move_duration = Duration::from_millis(2_000); let action = action::Sequence::new(vec![ action::Show::new(&self.layers.fg, &sprite).boxed(), action::MoveBy::new(&sprite, delta, move_duration).boxed(), ]); action.boxed() } fn action_demo_show_hide(&self) -> Box<dyn Action> { let mut sprite = { let mut sprite = Sprite::from_text(("some text", self.assets.font), 0.1); sprite.set_pos(Vec2::new(0.0, 0.0)); sprite.set_scale(2.0); let scale = sprite.scale(); assert!((scale - 2.0).abs() < 0.001); sprite }; let visible = Color::new(0.0, 1.0, 0.0, 1.0); let invisible = Color::new(0.0, 1.0, 0.0, 0.0); sprite.set_color(invisible); let t = Duration::from_millis(1_000); let action = action::Sequence::new(vec![ action::Show::new(&self.layers.bg, &sprite).boxed(), action::ChangeColorTo::new(&sprite, visible, t).boxed(), action::Sleep::new(t).boxed(), action::ChangeColorTo::new(&sprite, invisible, t).boxed(), action::Hide::new(&self.layers.bg, &sprite).boxed(), ]); action.boxed() } } fn update_aspect_ratio() { let aspect_ratio = window::screen_width() / window::screen_height(); let coordinates = Rect::new(-aspect_ratio, -1.0, aspect_ratio * 2.0, 2.0); set_camera(&Camera2D::from_display_rect(coordinates)); } #[mq::main("ZScene: Actions Demo")] #[macroquad(crate_rename = "mq")] async fn main() { let assets = Assets::load().await.expect("Can't load assets"); let mut state = State::new(assets); { state.scene.add_action(state.action_demo_move()); state.scene.add_action(state.action_demo_show_hide()); } loop { window::clear_background(BLACK); update_aspect_ratio(); let dtime = time::get_frame_time(); state.scene.tick(Duration::from_secs_f32(dtime)); state.scene.draw(); window::next_frame().await; } }
use std::time::Duration; use mq::{ camera::{set_camera, Camera2D}, color::{Color, BLACK}, math::{Rect, Vec2}, text, texture::{self, Texture2D}, time, window, }; use zscene::{self, action, Action, Boxed, Layer, Scene, Sprite}; #[derive(Debug)] pub enum Err { File(mq::file::FileError), Font(mq::text::FontError), } impl From<mq::file::FileError> for Err { fn from(err: mq::file::FileError) -> Self { Err::File(err) } } impl From<mq::text::FontError> for Err { fn from(err: mq::text::FontError) -> Self { Err::Font(err) } } #[derive(Debug, Clone, Default)] pub struct Layers { pub bg: Layer, pub fg: Layer, } impl Layers { fn sorted(self) -> Vec<Layer> { vec![self.bg, self.fg] } } struct Assets { font: text::Font, texture: Texture2D, } impl Assets { async fn load() -> Result<Self, Err> { let font = text::load_ttf_font("zscene/assets/Karla-Regular.ttf").await?; let texture = texture::load_texture("zscene/assets/fire.png").await?; Ok(Self { font, texture }) } } struct State { assets: Assets, scene: Scene, layers: Layers, } impl State { fn new(assets: Assets) -> Self { let layers = Layers::default(); let scene = Scene::new(layers.clone().sorted()); update_aspect_ratio(); Self { assets, scene, layers, } } fn action_demo_move(&self) -> Box<dyn Action> { let mut sprite = Sprite::from_texture(self.assets.texture, 0.5); sprite.set_pos(Vec2::new(0.0, -1.0)); let delta = Vec2::new(0.0, 1.5); let move_duration = Duration::from_millis(2_000); let action = action::Sequence::new(vec![ action::Show::new(&self.layers.fg, &sprite).boxed(), action::MoveBy::new(&sprite, delta, move_duration).boxed(), ]); action.boxed() } fn action_demo_show_hide(&self) -> Box<dyn Action> { let mut sprite = { let mut sprite = Sprite::from_text(("some text", self.assets.font), 0.1); sprite.set_pos(Vec2::new(0.0, 0.0)); sprite.set_scale(2.0); let scale = sprite.scale(); assert!((scale - 2.0).abs() < 0.001); sprite }; let visible = Color::new(0.0, 1.0, 0.0, 1.0); let invisible = Color::new(0.0, 1.0, 0.0, 0.0); sprite.set_color(invisible); let t = Duration::from_millis(1_000); let action = action::Sequence::new(vec![ action::Show::new(&self.layers.bg, &sprite).boxed(), action::ChangeColorTo::new(&sprite, visible, t).boxed(), action::Sleep::new(t).boxed(), action::ChangeColorTo::new(&sprite, invisible, t).boxed(), action::Hide::new(&self.layers.bg, &sprite).boxed(), ]); action.boxed() } } fn update_aspect_ratio() { let aspect_ratio = window::screen_width() / window::screen_height(); let coordinates = Rect::new(-aspect_ratio, -1.0, aspect_ratio * 2.0, 2.0); set_camera(&Camera2D::from_display_rect(coordinates)); } #[mq::main("ZScene: Actions Demo")] #[macroquad(crate_rename = "mq")] async fn main() { let assets = Assets::load().await.expect("Can't load assets"); let m
ut state = State::new(assets); { state.scene.add_action(state.action_demo_move()); state.scene.add_action(state.action_demo_show_hide()); } loop { window::clear_background(BLACK); update_aspect_ratio(); let dtime = time::get_frame_time(); state.scene.tick(Duration::from_secs_f32(dtime)); state.scene.draw(); window::next_frame().await; } }
function_block-function_prefixed
[ { "content": "fn arc_move(view: &mut BattleView, sprite: &Sprite, diff: Vec2) -> Box<dyn Action> {\n\n let len = diff.length();\n\n let min_height = view.tile_size() * 0.5;\n\n let base_height = view.tile_size() * 2.0;\n\n let min_time = 0.25;\n\n let base_time = 0.3;\n\n let height = min_heig...
Rust
src/decomposition/lu.rs
vinesystems/lair
b28b0949ae8bcf49bb58c665df0d24e0b6dab90b
use crate::{lapack, InvalidInput, Real, Scalar}; use ndarray::{s, Array1, Array2, ArrayBase, Data, DataMut, Ix1, Ix2}; use std::cmp; use std::fmt; #[derive(Debug)] pub struct Factorized<A, S> where A: fmt::Debug, S: Data<Elem = A>, { lu: ArrayBase<S, Ix2>, pivots: Vec<usize>, singular: Option<usize>, } impl<A, S> Factorized<A, S> where A: Scalar, S: Data<Elem = A>, { pub fn p(&self) -> Array2<A> { let permutation = { let mut permutation = (0..self.lu.nrows()).collect::<Vec<_>>(); unsafe { lapack::laswp(1, permutation.as_mut_ptr(), 1, 1, 0, &self.pivots) }; permutation }; let mut p = Array2::zeros((self.lu.nrows(), self.lu.nrows())); for (i, pivot) in permutation.iter().enumerate() { p[(*pivot, i)] = A::one(); } p } pub fn l(&self) -> Array2<A> { let rank = cmp::min(self.lu.nrows(), self.lu.ncols()); let mut l = Array2::zeros((self.lu.nrows(), rank)); for i in 0..self.lu.nrows() { for j in 0..i { l[(i, j)] = self.lu[(i, j)]; } if i < rank { l[(i, i)] = A::one(); for j in i + 1..rank { l[(i, j)] = A::zero(); } } } l } pub fn u(&self) -> Array2<A> { let rank = cmp::min(self.lu.nrows(), self.lu.ncols()); let mut u = Array2::zeros((rank, self.lu.ncols())); for i in 0..rank { for j in 0..i { u[(i, j)] = A::zero(); } for j in i..self.lu.ncols() { u[(i, j)] = self.lu[(i, j)]; } } u } pub fn is_singular(&self) -> bool { self.singular.is_some() } pub fn solve<SB>(&self, b: &ArrayBase<SB, Ix1>) -> Result<Array1<A>, InvalidInput> where SB: Data<Elem = A>, { if b.len() != self.lu.nrows() { return Err(InvalidInput::Shape(format!( "b must have {} elements", self.lu.nrows() ))); } Ok(lapack::getrs(&self.lu, &self.pivots, b)) } } impl<A, S> Factorized<A, S> where A: Scalar, S: DataMut<Elem = A>, { pub fn into_pl(mut self) -> ArrayBase<S, Ix2> { if self.pivots.len() < self.lu.nrows() { let next = self.pivots.len(); self.pivots.extend(next..self.lu.nrows()); } for i in (0..self.pivots.len()).rev() { let target = self.pivots[i]; if i == target { continue; } self.pivots[i] = self.pivots[target]; self.pivots[target] = i; } let mut pl = self .lu .slice_mut(s![.., ..cmp::min(self.lu.nrows(), self.lu.ncols())]); let mut dst = 0; let mut i = dst; loop { let src = self.pivots[dst]; for k in 0..cmp::min(src, pl.ncols()) { pl[[dst, k]] = pl[[src, k]]; } if src < pl.ncols() { pl[[dst, src]] = A::one(); } for k in src + 1..pl.ncols() { pl[[dst, k]] = A::zero(); } self.pivots[dst] = self.pivots.len(); if self.pivots[src] == self.pivots.len() { dst = i + 1; while dst < self.pivots.len() && self.pivots[dst] == self.pivots.len() { dst += 1; } if dst == self.pivots.len() { break; } i = dst; } else { dst = src; } } self.lu } } impl<A, S> From<ArrayBase<S, Ix2>> for Factorized<A, S> where A: Scalar, A::Real: Real, S: DataMut<Elem = A>, { fn from(mut a: ArrayBase<S, Ix2>) -> Self { let (pivots, singular) = lapack::getrf(a.view_mut()); Factorized { lu: a, pivots, singular, } } } #[cfg(test)] mod tests { use approx::assert_relative_eq; use ndarray::{arr2, s}; use std::cmp; #[test] fn square() { let a = arr2(&[ [1_f32, 2_f32, 3_f32], [2_f32, 2_f32, 1_f32], [3_f32, 1_f32, 2_f32], ]); let lu = super::Factorized::from(a); let p = lu.p(); assert_eq!(p[(0, 1)], 1.); assert_eq!(p[(1, 2)], 1.); assert_eq!(p[(2, 0)], 1.); let l = lu.l(); assert_relative_eq!(l[(0, 0)], 1., max_relative = 1e-6); assert_relative_eq!(l[(1, 0)], 0.33333333, max_relative = 1e-6); assert_relative_eq!(l[(2, 0)], 0.66666666, max_relative = 1e-6); let u = lu.u(); assert_relative_eq!(u[(0, 2)], 2., max_relative = 1e-6); assert_relative_eq!(u[(1, 2)], 2.33333333, max_relative = 1e-6); assert_relative_eq!(u[(2, 2)], -2.2, max_relative = 1e-6); } #[test] fn wide() { let a = arr2(&[ [1_f32, 2_f32, 3_f32, 1_f32], [2_f32, 2_f32, 1_f32, 3_f32], [3_f32, 1_f32, 2_f32, 2_f32], ]); let lu = super::Factorized::from(a); let p = lu.p(); assert_eq!(p.shape(), &[3, 3]); assert_eq!(p[(0, 1)], 1.); assert_eq!(p[(1, 2)], 1.); assert_eq!(p[(2, 0)], 1.); let l = lu.l(); assert_eq!(l.shape(), &[3, 3]); assert_relative_eq!(l[(0, 0)], 1., max_relative = 1e-6); assert_relative_eq!(l[(1, 0)], 0.33333333, max_relative = 1e-6); assert_relative_eq!(l[(2, 0)], 0.66666666, max_relative = 1e-6); let u = lu.u(); assert_eq!(u.shape(), &[3, 4]); assert_relative_eq!(u[(0, 2)], 2., max_relative = 1e-6); assert_relative_eq!(u[(1, 2)], 2.33333333, max_relative = 1e-6); assert_relative_eq!(u[(2, 2)], -2.2, max_relative = 1e-6); } #[test] fn tall() { let a = arr2(&[ [1_f32, 2_f32, 3_f32], [2_f32, 2_f32, 1_f32], [3_f32, 1_f32, 2_f32], [2_f32, 3_f32, 3_f32], ]); let lu = super::Factorized::from(a); let p = lu.p(); assert_eq!(p.shape(), &[4, 4]); assert_eq!(p[(0, 3)], 1.); assert_eq!(p[(1, 2)], 1.); assert_eq!(p[(2, 0)], 1.); assert_eq!(p[(3, 1)], 1.); let l = lu.l(); assert_eq!(l.shape(), &[4, 3]); assert_relative_eq!(l[(0, 0)], 1., max_relative = 1e-6); assert_relative_eq!(l[(1, 0)], 0.66666666, max_relative = 1e-6); assert_relative_eq!(l[(2, 0)], 0.66666666, max_relative = 1e-6); assert_relative_eq!(l[(3, 0)], 0.33333333, max_relative = 1e-6); let u = lu.u(); assert_eq!(u.shape(), &[3, 3]); assert_relative_eq!(u[(0, 2)], 2., max_relative = 1e-6); assert_relative_eq!(u[(1, 2)], 1.66666666, max_relative = 1e-6); assert_relative_eq!(u[(2, 2)], -1.28571429, max_relative = 1e-6); } #[test] fn lu_pl_identity_l() { let p = [ [0_f32, 1_f32, 0_f32], [0_f32, 0_f32, 1_f32], [1_f32, 0_f32, 0_f32], ]; let m = arr2(&p); let k = cmp::min(m.nrows(), m.ncols()); let pl = super::Factorized::from(m).into_pl(); assert_eq!(pl.slice(s![.., ..k]), arr2(&p)); } #[test] fn lu_pl_singular() { let m = arr2(&[[0_f32, 0_f32], [3_f32, 4_f32], [6_f32, 8_f32]]); let k = cmp::min(m.nrows(), m.ncols()); let pl = super::Factorized::from(m).into_pl(); assert_eq!( pl.slice(s![.., ..k]), arr2(&[[0., 0.], [0.5, 1.], [1., 0.]]) ); } #[test] fn lu_pl_square() { let m = arr2(&[ [0_f32, 1_f32, 2_f32], [1_f32, 2_f32, 3_f32], [2_f32, 3_f32, 4_f32], ]); let k = cmp::min(m.nrows(), m.ncols()); let pl = super::Factorized::from(m).into_pl(); assert_eq!( pl.slice(s![.., ..k]), arr2(&[[0., 1., 0.], [0.5, 0.5, 1.], [1., 0., 0.]]) ); } #[test] fn lu_pl_tall_l() { let m = arr2(&[[0_f32, 1_f32], [1_f32, 2_f32], [2_f32, 3_f32]]); let k = cmp::min(m.nrows(), m.ncols()); let pl = super::Factorized::from(m).into_pl(); assert_eq!( pl.slice(s![.., ..k]), arr2(&[[0., 1.], [0.5, 0.5], [1., 0.]]) ); } #[test] fn lu_pl_wide_u() { let m = arr2(&[[0_f32, 1_f32, 2_f32], [1_f32, 2_f32, 3_f32]]); let k = cmp::min(m.nrows(), m.ncols()); let pl = super::Factorized::from(m).into_pl(); assert_eq!(pl.slice(s![.., ..k]), arr2(&[[0., 1.], [1., 0.]])); } }
use crate::{lapack, InvalidInput, Real, Scalar}; use ndarray::{s, Array1, Array2, ArrayBase, Data, DataMut, Ix1, Ix2}; use std::cmp; use std::fmt; #[derive(Debug)] pub struct Factorized<A, S> where A: fmt::Debug, S: Data<Elem = A>, { lu: ArrayBase<S, Ix2>, pivots: Vec<usize>, singular: Option<usize>, } impl<A, S> Factorized<A, S> where A: Scalar, S: Data<Elem = A>, { pub fn p(&self) -> Array2<A> { let permutation = { let mut permutation = (0..self.lu.nrows()).collect::<Vec<_>>(); unsafe { lapack::laswp(1, permutation.as_mut_ptr(), 1, 1, 0, &self.pivots) }; permutation }; let mut p = Array2::zeros((self.lu.nrows(), self.lu.nrows())); for (i, pivot) in permutation.iter().enumerate() { p[(*pivot, i)] = A::one(); } p } pub fn l(&self) -> Array2<A> { let rank = cmp::min(self.lu.nrows(), self.lu.ncols()); let mut l = Array2::zeros((self.lu.nrows(), rank)); for i in 0..self.lu.nrows() { for j in 0..i { l[(i, j)] = self.lu[(i, j)]; } if i < rank { l[(i, i)] = A::one(); for j in i + 1..rank { l[(i, j)] = A::zero(); } } } l } pub fn u(&self) -> Array2<A> { let rank = cmp::min(self.lu.nrows(), self.lu.ncols()); let mut u = Array2::zeros((rank, self.lu.ncols())); for i in 0..rank { for j in 0..i { u[(i, j)] = A::zero(); } for j in i..self.lu.ncols() { u[(i, j)] = self.lu[(i, j)]; } } u } pub fn is_singular(&self) -> bool { self.singular.is_some() } pub fn solve<SB>(&self, b: &ArrayBase<SB, Ix1>) -> Result<Array1<A>, InvalidInput> where SB: Data<Elem = A>, { if b.len() != self.lu.nrows() { return Err(InvalidInput::Shape(format!( "b must have {} elements", self.lu.nrows() ))); } Ok(lapack::getrs(&self.lu, &self.pivots, b)) } } impl<A, S> Factorized<A, S> where A: Scalar, S: DataMut<Elem = A>, { pub fn into_pl(mut self) -> ArrayBase<S, Ix2> { if self.pivots.len() < self.lu.nrows() { let next = self.pivots.len(); self.pivots.extend(next..self.lu.nrows()); } for i in (0..self.pivots.len()).rev() { let target = self.pivots[i]; if i == target { continue; } self.pivots[i] = self.pivots[target]; self.pivots[target] = i; } let mut pl = self .lu .slice_mut(s![.., ..cmp::min(self.lu.nrows(), self.lu.ncols())]); let mut dst = 0; let mut i = dst; loop { let src = self.pivots[dst]; for k in 0..cmp::min(src, pl.ncols()) { pl[[dst, k]] = pl[[src, k]]; } if src < pl.ncols() { pl[[dst, src]] = A::one(); } for k in src + 1..pl.ncols() { pl[[dst, k]] = A::zero(); } self.pivots[dst] = self.pivots.len(); if self.pivots[src] == self.pivots.len() { dst = i + 1; while dst < self.pivots.len() && self.pivots[dst] == self.pivots.len() { dst += 1; } if dst == self.pivots.len() { break; } i = dst; } else { dst = src; } } self.lu } } impl<A, S> From<ArrayBase<S, Ix2>> for Factorized<A, S> where A: Scalar, A::Real: Real, S: DataMut<Elem = A>, {
} #[cfg(test)] mod tests { use approx::assert_relative_eq; use ndarray::{arr2, s}; use std::cmp; #[test] fn square() { let a = arr2(&[ [1_f32, 2_f32, 3_f32], [2_f32, 2_f32, 1_f32], [3_f32, 1_f32, 2_f32], ]); let lu = super::Factorized::from(a); let p = lu.p(); assert_eq!(p[(0, 1)], 1.); assert_eq!(p[(1, 2)], 1.); assert_eq!(p[(2, 0)], 1.); let l = lu.l(); assert_relative_eq!(l[(0, 0)], 1., max_relative = 1e-6); assert_relative_eq!(l[(1, 0)], 0.33333333, max_relative = 1e-6); assert_relative_eq!(l[(2, 0)], 0.66666666, max_relative = 1e-6); let u = lu.u(); assert_relative_eq!(u[(0, 2)], 2., max_relative = 1e-6); assert_relative_eq!(u[(1, 2)], 2.33333333, max_relative = 1e-6); assert_relative_eq!(u[(2, 2)], -2.2, max_relative = 1e-6); } #[test] fn wide() { let a = arr2(&[ [1_f32, 2_f32, 3_f32, 1_f32], [2_f32, 2_f32, 1_f32, 3_f32], [3_f32, 1_f32, 2_f32, 2_f32], ]); let lu = super::Factorized::from(a); let p = lu.p(); assert_eq!(p.shape(), &[3, 3]); assert_eq!(p[(0, 1)], 1.); assert_eq!(p[(1, 2)], 1.); assert_eq!(p[(2, 0)], 1.); let l = lu.l(); assert_eq!(l.shape(), &[3, 3]); assert_relative_eq!(l[(0, 0)], 1., max_relative = 1e-6); assert_relative_eq!(l[(1, 0)], 0.33333333, max_relative = 1e-6); assert_relative_eq!(l[(2, 0)], 0.66666666, max_relative = 1e-6); let u = lu.u(); assert_eq!(u.shape(), &[3, 4]); assert_relative_eq!(u[(0, 2)], 2., max_relative = 1e-6); assert_relative_eq!(u[(1, 2)], 2.33333333, max_relative = 1e-6); assert_relative_eq!(u[(2, 2)], -2.2, max_relative = 1e-6); } #[test] fn tall() { let a = arr2(&[ [1_f32, 2_f32, 3_f32], [2_f32, 2_f32, 1_f32], [3_f32, 1_f32, 2_f32], [2_f32, 3_f32, 3_f32], ]); let lu = super::Factorized::from(a); let p = lu.p(); assert_eq!(p.shape(), &[4, 4]); assert_eq!(p[(0, 3)], 1.); assert_eq!(p[(1, 2)], 1.); assert_eq!(p[(2, 0)], 1.); assert_eq!(p[(3, 1)], 1.); let l = lu.l(); assert_eq!(l.shape(), &[4, 3]); assert_relative_eq!(l[(0, 0)], 1., max_relative = 1e-6); assert_relative_eq!(l[(1, 0)], 0.66666666, max_relative = 1e-6); assert_relative_eq!(l[(2, 0)], 0.66666666, max_relative = 1e-6); assert_relative_eq!(l[(3, 0)], 0.33333333, max_relative = 1e-6); let u = lu.u(); assert_eq!(u.shape(), &[3, 3]); assert_relative_eq!(u[(0, 2)], 2., max_relative = 1e-6); assert_relative_eq!(u[(1, 2)], 1.66666666, max_relative = 1e-6); assert_relative_eq!(u[(2, 2)], -1.28571429, max_relative = 1e-6); } #[test] fn lu_pl_identity_l() { let p = [ [0_f32, 1_f32, 0_f32], [0_f32, 0_f32, 1_f32], [1_f32, 0_f32, 0_f32], ]; let m = arr2(&p); let k = cmp::min(m.nrows(), m.ncols()); let pl = super::Factorized::from(m).into_pl(); assert_eq!(pl.slice(s![.., ..k]), arr2(&p)); } #[test] fn lu_pl_singular() { let m = arr2(&[[0_f32, 0_f32], [3_f32, 4_f32], [6_f32, 8_f32]]); let k = cmp::min(m.nrows(), m.ncols()); let pl = super::Factorized::from(m).into_pl(); assert_eq!( pl.slice(s![.., ..k]), arr2(&[[0., 0.], [0.5, 1.], [1., 0.]]) ); } #[test] fn lu_pl_square() { let m = arr2(&[ [0_f32, 1_f32, 2_f32], [1_f32, 2_f32, 3_f32], [2_f32, 3_f32, 4_f32], ]); let k = cmp::min(m.nrows(), m.ncols()); let pl = super::Factorized::from(m).into_pl(); assert_eq!( pl.slice(s![.., ..k]), arr2(&[[0., 1., 0.], [0.5, 0.5, 1.], [1., 0., 0.]]) ); } #[test] fn lu_pl_tall_l() { let m = arr2(&[[0_f32, 1_f32], [1_f32, 2_f32], [2_f32, 3_f32]]); let k = cmp::min(m.nrows(), m.ncols()); let pl = super::Factorized::from(m).into_pl(); assert_eq!( pl.slice(s![.., ..k]), arr2(&[[0., 1.], [0.5, 0.5], [1., 0.]]) ); } #[test] fn lu_pl_wide_u() { let m = arr2(&[[0_f32, 1_f32, 2_f32], [1_f32, 2_f32, 3_f32]]); let k = cmp::min(m.nrows(), m.ncols()); let pl = super::Factorized::from(m).into_pl(); assert_eq!(pl.slice(s![.., ..k]), arr2(&[[0., 1.], [1., 0.]])); } }
fn from(mut a: ArrayBase<S, Ix2>) -> Self { let (pivots, singular) = lapack::getrf(a.view_mut()); Factorized { lu: a, pivots, singular, } }
function_block-function_prefix_line
[ { "content": "/// Solves `a * x = b`.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the number of rows in `a` is different from the number of elements\n\n/// in `p` or the number of elements in `b`, or the number of columns in `a` is\n\n/// smaller than the number of elements in `p`.\n\npub fn getrs<A, SA, SB>...
Rust
lib/src/parser.rs
mkfoo/midilisp
d08093c70b0037f8f221be75c46e7b1f1ef1ed6c
use crate::{ error::{Error, Result}, lexer::{Lexer, Token}, value::Value, FnvIndexSet, }; use smol_str::SmolStr; use std::cmp::PartialEq; use Token::*; pub type AstPtr = u32; pub type StrId = u32; pub const NIL: AstPtr = 0; const LPAR: AstPtr = 1; #[derive(Debug, Clone, Copy, PartialEq)] pub enum Expr { Atom(Value), Cons(AstPtr, AstPtr), } pub struct Parser { ast: Vec<Expr>, stack: Vec<AstPtr>, strings: FnvIndexSet<SmolStr>, pub line: Option<u32>, } impl Parser { pub fn new() -> Self { Self { ast: vec![Expr::Atom(Value::Nil), Expr::Atom(Value::Nil)], stack: Vec::new(), strings: Default::default(), line: Some(1), } } fn push_expr(&mut self, e: Expr) -> AstPtr { self.ast.push(e); (self.ast.len() - 1) as AstPtr } pub fn get(&self, ptr: AstPtr) -> Expr { *self.ast.get(ptr as usize).expect("BUG: invalid ast ptr") } pub fn add_str(&mut self, s: &str) -> StrId { self.strings.insert_full(SmolStr::new(s)).0 as StrId } pub fn get_str(&self, id: StrId) -> &str { self.strings .get_index(id as usize) .map(|s| s.as_str()) .expect("BUG: invalid str id") } pub fn parse(&mut self, src: &str) -> Result<Vec<AstPtr>> { let mut lex = Lexer::new(src); let mut exprs = Vec::new(); while let Some(tok) = lex.next() { self.line = Some(lex.line); match tok { LeftParen => exprs.push(self.cons(&mut lex)?), RightParen => return Err(Error::InvalidParen), _ => exprs.push(self.atom(tok, &lex)?), } } self.line = None; Ok(exprs) } fn cons(&mut self, lex: &mut Lexer) -> Result<AstPtr> { self.stack.push(LPAR); while self.stack[0] == LPAR { let tok = lex.next(); self.line = Some(lex.line); match tok { Some(LeftParen) => self.stack.push(LPAR), Some(RightParen) => { let cons = self.fold()?; self.stack.push(cons); } Some(tok) => { let a = self.atom(tok, lex)?; self.stack.push(a); } None => return Err(Error::UnclosedParen), } } Ok(self.stack.pop().unwrap()) } fn fold(&mut self) -> Result<AstPtr> { let mut cdr = NIL; loop { match self.stack.pop() { Some(LPAR) => return Ok(cdr), Some(car) => cdr = self.push_expr(Expr::Cons(car, cdr)), None => return Err(Error::InvalidParen), } } } fn atom(&mut self, tok: Token, lex: &Lexer) -> Result<AstPtr> { let s = lex.get_str(); let val = match tok { Ident => Value::Ident(self.add_str(s)), Str => Value::Str(self.add_str(s)), Int => Value::parse_int(s)?, Float => Value::parse_float(s)?, Hex => Value::parse_hex(s)?, Bin => Value::parse_bin(s)?, StrError => return Err(Error::UnclosedStr), NumError => return Err(Error::ParseNum), _ => unreachable!(), }; Ok(self.push_expr(Expr::Atom(val))) } } #[cfg(test)] mod tests { use super::{AstPtr, Expr, Parser, NIL}; use crate::error::Error; use crate::value::Value; use Expr::*; use Value::*; fn exp_cons(p: &Parser, e: AstPtr) -> (AstPtr, AstPtr) { match p.get(e) { Cons(car, cdr) => (car, cdr), _ => panic!(), } } #[test] fn literals() { let src = "5 -5 0xff 0b1010 0.5 .5"; let mut parser = Parser::new(); let exprs = parser.parse(src).unwrap(); assert_eq!(Atom(I32(5)), parser.get(exprs[0])); assert_eq!(Atom(I32(-5)), parser.get(exprs[1])); assert_eq!(Atom(U32(0xff)), parser.get(exprs[2])); assert_eq!(Atom(U32(0b1010)), parser.get(exprs[3])); assert_eq!(Atom(F32(0.5)), parser.get(exprs[4])); assert_eq!(Atom(F32(0.5)), parser.get(exprs[5])); } #[test] fn list() { let src = "(1 2 3)"; let mut parser = Parser::new(); let exprs = parser.parse(src).unwrap(); let (car, cdr) = exp_cons(&parser, exprs[0]); assert_eq!(Atom(I32(1)), parser.get(car)); let (car, cdr) = exp_cons(&parser, cdr); assert_eq!(Atom(I32(2)), parser.get(car)); let (car, cdr) = exp_cons(&parser, cdr); assert_eq!(Atom(I32(3)), parser.get(car)); assert_eq!(NIL, cdr); } #[test] fn tree() { let src = "((1 2) 3 4)"; let mut parser = Parser::new(); let exprs = parser.parse(src).unwrap(); let (car0, cdr0) = exp_cons(&parser, exprs[0]); let (one, cdr1) = exp_cons(&parser, car0); let (two, nil0) = exp_cons(&parser, cdr1); let (three, cdr2) = exp_cons(&parser, cdr0); let (four, nil1) = exp_cons(&parser, cdr2); assert_eq!(Atom(I32(1)), parser.get(one)); assert_eq!(Atom(I32(2)), parser.get(two)); assert_eq!(Atom(I32(3)), parser.get(three)); assert_eq!(Atom(I32(4)), parser.get(four)); assert_eq!(NIL, nil0); assert_eq!(NIL, nil1); } #[test] fn seq() { let src = "(1 2) (3 4)"; let mut parser = Parser::new(); let exprs = parser.parse(src).unwrap(); let (one, cdr) = exp_cons(&parser, exprs[0]); assert_eq!(Atom(I32(1)), parser.get(one)); let (two, nil) = exp_cons(&parser, cdr); assert_eq!(Atom(I32(2)), parser.get(two)); assert_eq!(NIL, nil); let (three, cdr) = exp_cons(&parser, exprs[1]); assert_eq!(Atom(I32(3)), parser.get(three)); let (four, nil) = exp_cons(&parser, cdr); assert_eq!(Atom(I32(4)), parser.get(four)); assert_eq!(NIL, nil); } #[test] fn errors() { let src1 = "(1 2))(3 4)"; let src2 = "((1 2 3 4)"; { let mut parser = Parser::new(); assert_eq!(Error::InvalidParen, parser.parse(src1).unwrap_err()); } { let mut parser = Parser::new(); assert_eq!(Error::UnclosedParen, parser.parse(src2).unwrap_err()); } } }
use crate::{ error::{Error, Result}, lexer::{Lexer, Token}, value::Value, FnvIndexSet, }; use smol_str::SmolStr; use std::cmp::PartialEq; use Token::*; pub type AstPtr = u32; pub type StrId = u32; pub const NIL: AstPtr = 0; const LPAR: AstPtr = 1; #[derive(Debug, Clone, Copy, PartialEq)] pub enum Expr { Atom(Value), Cons(AstPtr, AstPtr), } pub struct Parser { ast: Vec<Expr>, stack: Vec<AstPtr>, strings: FnvIndexSet<SmolStr>, pub line: Option<u32>, } impl Parser { pub fn new() -> Self { Self { ast: vec![Expr::Atom(Value::Nil), Expr::Atom(Value::Nil)], stack: Vec::new(), strings: Default::default(), line: Some(1), } } fn push_expr(&mut self, e: Expr) -> AstPtr { self.ast.push(e); (self.ast.len() - 1) as AstPtr } pub fn get(&self, ptr: AstPtr) -> Expr { *self.ast.get(ptr as usize).expect("BUG: invalid ast ptr") } pub fn add_str(&mut self, s: &str) -> StrId { self.strings.insert_full(SmolStr::new(s)).0 as StrId } pub fn get_str(&self, id: StrId) -> &str { self.strings .get_index(id as usize) .map(|s| s.as_str()) .expect("BUG: invalid str id") } pub fn parse(&mut self, src: &str) -> Result<Vec<AstPtr>> { let mut lex = Lexer::new(src); let mut exprs = Vec::new(); while let Some(tok) = lex.next() { self.line = Some(lex.line); match tok { LeftParen => exprs.push(self.cons(&mut lex)?), RightParen => return Err(Error::InvalidParen), _ => exprs.push(self.atom(tok, &lex)?), } } self.line = None; Ok(exprs) } fn cons(&mut self, lex: &mut Lexer) -> Result<AstPtr> { self.stack.push(LPAR); while self.stack[0] == LPAR { let tok = lex.next(); self.line = Some(lex.line); match tok { Some(LeftParen) => self.stack.push(LPAR), Some(RightParen) => { let cons = self.fold()?; self.stack.push(cons); } Some(tok) => { let a = self.atom(tok, lex)?; self.stack.push(a); } None => return Err(Error::UnclosedParen), } } Ok(self.stack.pop().unwrap()) } fn fold(&mut self) -> Result<AstPtr> { let mut cdr = NIL; loop { match self.stack.pop() { Some(LPAR) => return Ok(cdr), Some(car) => cdr = self.push_expr(Expr::Cons(car, cdr)), None => return Err(Error::InvalidParen), } } } fn atom(&mut self, tok: Token, lex: &Lexer) -> Result<AstPtr> { let s = lex.get_str(); let val = match tok { Ident => Value::Ident(self.add_str(s)), Str => Value::Str(self.add_str(s)), Int => Value::parse_int(s)?, Float => Value::parse_float(s)?, Hex => Value::parse_hex(s)?, Bin => Value::parse_bin(s)?, StrError => return Err(Error::UnclosedStr), NumError => return Err(Error::ParseNum), _ => unreachable!(), }; Ok(self.push_expr(Expr::Atom(val))) } } #[cfg(test)] mod tests { use super::{AstPtr, Expr, Parser, NIL}; use crate::error::Error; use crate::value::Value; use Expr::*; use Value::*; fn exp_cons(p: &Parser, e: AstPtr) -> (AstPtr, AstPtr) { match p.get(e) { Cons(car, cdr) => (car, cdr), _ => panic!(), } } #[test]
#[test] fn list() { let src = "(1 2 3)"; let mut parser = Parser::new(); let exprs = parser.parse(src).unwrap(); let (car, cdr) = exp_cons(&parser, exprs[0]); assert_eq!(Atom(I32(1)), parser.get(car)); let (car, cdr) = exp_cons(&parser, cdr); assert_eq!(Atom(I32(2)), parser.get(car)); let (car, cdr) = exp_cons(&parser, cdr); assert_eq!(Atom(I32(3)), parser.get(car)); assert_eq!(NIL, cdr); } #[test] fn tree() { let src = "((1 2) 3 4)"; let mut parser = Parser::new(); let exprs = parser.parse(src).unwrap(); let (car0, cdr0) = exp_cons(&parser, exprs[0]); let (one, cdr1) = exp_cons(&parser, car0); let (two, nil0) = exp_cons(&parser, cdr1); let (three, cdr2) = exp_cons(&parser, cdr0); let (four, nil1) = exp_cons(&parser, cdr2); assert_eq!(Atom(I32(1)), parser.get(one)); assert_eq!(Atom(I32(2)), parser.get(two)); assert_eq!(Atom(I32(3)), parser.get(three)); assert_eq!(Atom(I32(4)), parser.get(four)); assert_eq!(NIL, nil0); assert_eq!(NIL, nil1); } #[test] fn seq() { let src = "(1 2) (3 4)"; let mut parser = Parser::new(); let exprs = parser.parse(src).unwrap(); let (one, cdr) = exp_cons(&parser, exprs[0]); assert_eq!(Atom(I32(1)), parser.get(one)); let (two, nil) = exp_cons(&parser, cdr); assert_eq!(Atom(I32(2)), parser.get(two)); assert_eq!(NIL, nil); let (three, cdr) = exp_cons(&parser, exprs[1]); assert_eq!(Atom(I32(3)), parser.get(three)); let (four, nil) = exp_cons(&parser, cdr); assert_eq!(Atom(I32(4)), parser.get(four)); assert_eq!(NIL, nil); } #[test] fn errors() { let src1 = "(1 2))(3 4)"; let src2 = "((1 2 3 4)"; { let mut parser = Parser::new(); assert_eq!(Error::InvalidParen, parser.parse(src1).unwrap_err()); } { let mut parser = Parser::new(); assert_eq!(Error::UnclosedParen, parser.parse(src2).unwrap_err()); } } }
fn literals() { let src = "5 -5 0xff 0b1010 0.5 .5"; let mut parser = Parser::new(); let exprs = parser.parse(src).unwrap(); assert_eq!(Atom(I32(5)), parser.get(exprs[0])); assert_eq!(Atom(I32(-5)), parser.get(exprs[1])); assert_eq!(Atom(U32(0xff)), parser.get(exprs[2])); assert_eq!(Atom(U32(0b1010)), parser.get(exprs[3])); assert_eq!(Atom(F32(0.5)), parser.get(exprs[4])); assert_eq!(Atom(F32(0.5)), parser.get(exprs[5])); }
function_block-full_function
[ { "content": "type BuiltinFn<T> = fn(&mut T, AstPtr) -> Result<Value>;\n", "file_path": "lib/src/interpreter.rs", "rank": 0, "score": 173176.83868602625 }, { "content": "type LexFn<T> = fn(&mut T) -> Token;\n\n\n\npub struct Lexer<'a> {\n\n f: LexFn<Self>,\n\n iter: CharIndices<'a>,\n\...
Rust
src/tcp/hole_punch/puncher.rs
nbaksalyar/p2p
fbdc95585ee180af2d15c1e135de08021c6510db
use mio::tcp::TcpStream; use mio::timer::Timeout; use mio::{Poll, PollOpt, Ready, Token}; use net2::TcpStreamExt; use socket_collection::TcpSock; use sodium::crypto::box_; use std::any::Any; use std::cell::RefCell; use std::mem; use std::net::SocketAddr; use std::rc::Rc; use std::time::{Duration, Instant}; use tcp::new_reusably_bound_tcp_sockets; use {Interface, NatError, NatState, NatTimer}; pub type Finish = Box<FnMut(&mut Interface, &Poll, Token, ::Res<(TcpSock, Duration)>)>; pub enum Via { Connect { our_addr: SocketAddr, peer_addr: SocketAddr, }, Accept(TcpSock, Token, Instant), } const TIMER_ID: u8 = 0; const RE_CONNECT_MS: u64 = 100; const CHOOSE_CONN: &[u8] = b"Choose this connection"; enum ConnectionChooser { Choose(Option<Vec<u8>>), Wait(box_::PrecomputedKey), } pub struct Puncher { token: Token, sock: TcpSock, our_addr: SocketAddr, peer_addr: SocketAddr, via_accept: bool, connection_chooser: ConnectionChooser, timeout: Option<Timeout>, commenced_at: Instant, f: Finish, } impl Puncher { pub fn start( ifc: &mut Interface, poll: &Poll, via: Via, peer_enc_pk: &box_::PublicKey, f: Finish, ) -> ::Res<Token> { let (sock, token, via_accept, our_addr, peer_addr, commenced_at) = match via { Via::Accept(sock, t, commenced_at) => { let our_addr = sock.local_addr()?; let peer_addr = sock.peer_addr()?; (sock, t, true, our_addr, peer_addr, commenced_at) } Via::Connect { our_addr, peer_addr, } => { let stream = new_reusably_bound_tcp_sockets(&our_addr, 1)?.0[0].to_tcp_stream()?; stream.set_linger(Some(Duration::from_secs(0)))?; let sock = TcpSock::wrap(TcpStream::connect_stream(stream, &peer_addr)?); ( sock, ifc.new_token(), false, our_addr, peer_addr, Instant::now(), ) } }; poll.register( &sock, token, Ready::readable() | Ready::writable(), PollOpt::edge(), )?; let key = box_::precompute(peer_enc_pk, ifc.enc_sk()); let chooser = if ifc.enc_pk() > peer_enc_pk { ConnectionChooser::Choose(Some(::msg_to_send(CHOOSE_CONN, &key)?)) } else { ConnectionChooser::Wait(key) }; let puncher = Rc::new(RefCell::new(Puncher { token, sock, our_addr, peer_addr, via_accept, connection_chooser: chooser, timeout: None, commenced_at, f, })); if let Err((nat_state, e)) = ifc.insert_state(token, puncher) { debug!("Error inserting state: {:?}", e); nat_state.borrow_mut().terminate(ifc, poll); return Err(NatError::TcpHolePunchFailed); } Ok(token) } fn read(&mut self, ifc: &mut Interface, poll: &Poll) { let mut ok = false; loop { match self.sock.read::<Vec<u8>>() { Ok(Some(cipher_text)) => { if let ConnectionChooser::Wait(ref key) = self.connection_chooser { match ::msg_to_read(&cipher_text, key) { Ok(ref plain_text) if plain_text == &CHOOSE_CONN => ok = true, _ => { debug!("Error: Failed to decrypt a connection-choose order"); ok = false; break; } } } else { debug!("Error: A chooser TcpPucher got a choose order"); ok = false; break; } } Ok(None) => { if ok { break; } else { return; } } Err(e) => { debug!("Tcp Puncher errored out in read: {:?}", e); ok = false; break; } } } if ok { self.done(ifc, poll) } else { self.handle_err(ifc, poll) } } fn write(&mut self, ifc: &mut Interface, poll: &Poll, m: Option<Vec<u8>>) { match self.sock.write(m.map(|m| (m, 0))) { Ok(true) => self.done(ifc, poll), Ok(false) => (), Err(e) => { debug!("Tcp Puncher errored out in write: {:?}", e); self.handle_err(ifc, poll); } } } fn done(&mut self, ifc: &mut Interface, poll: &Poll) { if let Some(t) = self.timeout.take() { let _ = ifc.cancel_timeout(&t); } let _ = ifc.remove_state(self.token); let sock = mem::replace(&mut self.sock, Default::default()); let dur = self.commenced_at.elapsed(); (*self.f)(ifc, poll, self.token, Ok((sock, dur))); } fn handle_err(&mut self, ifc: &mut Interface, poll: &Poll) { if self.via_accept { self.terminate(ifc, poll); (*self.f)(ifc, poll, self.token, Err(NatError::TcpHolePunchFailed)); } else { let _ = poll.deregister(&self.sock); let _ = mem::replace(&mut self.sock, Default::default()); if let Some(t) = self.timeout.take() { let _ = ifc.cancel_timeout(&t); } match ifc.set_timeout( Duration::from_millis(RE_CONNECT_MS), NatTimer::new(self.token, TIMER_ID), ) { Ok(t) => self.timeout = Some(t), Err(e) => { debug!("Error setting timeout: {:?}", e); self.terminate(ifc, poll); (*self.f)(ifc, poll, self.token, Err(NatError::TcpHolePunchFailed)); } } } } } impl NatState for Puncher { fn ready(&mut self, ifc: &mut Interface, poll: &Poll, event: Ready) { if event.is_readable() { self.read(ifc, poll) } else if event.is_writable() { if !self.via_accept { let r = || -> ::Res<TcpSock> { let sock = mem::replace(&mut self.sock, Default::default()); sock.set_linger(None)?; Ok(sock) }(); match r { Ok(s) => self.sock = s, Err(e) => { debug!("Terminating due to error: {:?}", e); self.terminate(ifc, poll); (*self.f)(ifc, poll, self.token, Err(NatError::TcpHolePunchFailed)); } } } let m = if let ConnectionChooser::Choose(ref mut m) = self.connection_chooser { m.take() } else { return; }; self.write(ifc, poll, m) } else { warn!("Investigate: Ignoring unknown event kind: {:?}", event); } } fn timeout(&mut self, ifc: &mut Interface, poll: &Poll, timer_id: u8) { if timer_id != TIMER_ID { debug!("Invalid timer id: {}", timer_id); } let r = || -> ::Res<TcpSock> { let stream = new_reusably_bound_tcp_sockets(&self.our_addr, 1)?.0[0].to_tcp_stream()?; stream.set_linger(Some(Duration::from_secs(0)))?; let sock = TcpSock::wrap(TcpStream::connect_stream(stream, &self.peer_addr)?); poll.register( &sock, self.token, Ready::readable() | Ready::writable(), PollOpt::edge(), )?; Ok(sock) }(); match r { Ok(s) => self.sock = s, Err(e) => { debug!("Aborting connection attempt due to: {:?}", e); self.terminate(ifc, poll); (*self.f)(ifc, poll, self.token, Err(NatError::TcpHolePunchFailed)); } } } fn terminate(&mut self, ifc: &mut Interface, poll: &Poll) { if let Some(t) = self.timeout.take() { let _ = ifc.cancel_timeout(&t); } let _ = ifc.remove_state(self.token); let _ = poll.deregister(&self.sock); } fn as_any(&mut self) -> &mut Any { self } }
use mio::tcp::TcpStream; use mio::timer::Timeout; use mio::{Poll, PollOpt, Ready, Token}; use net2::TcpStreamExt; use socket_collection::TcpSock; use sodium::crypto::box_; use std::any::Any; use std::cell::RefCell; use std::mem; use std::net::SocketAddr; use std::rc::Rc; use std::time::{Duration, Instant}; use tcp::new_reusably_bound_tcp_sockets; use {Interface, NatError, NatState, NatTimer}; pub type Finish = Box<FnMut(&mut Interface, &Poll, Token, ::Res<(TcpSock, Duration)>)>; pub enum Via { Connect { our_addr: SocketAddr, peer_addr: SocketAddr, }, Accept(TcpSock, Token, Instant), } const TIMER_ID: u8 = 0; const RE_CONNECT_MS: u64 = 100; const CHOOSE_CONN: &[u8] = b"Choose this connection"; enum ConnectionChooser { Choose(Option<Vec<u8>>), Wait(box_::PrecomputedKey), } pub struct Puncher { token: Token, sock: TcpSock, our_addr: SocketAddr, peer_addr: SocketAddr, via_accept: bool, connection_chooser: ConnectionChooser, timeout: Option<Timeout>, commenced_at: Instant, f: Finish, } impl Puncher { pub fn start( ifc: &mut Interface, poll: &Poll, via: Via, peer_enc_pk: &box_::PublicKey, f: Finish, ) -> ::Res<Token> { let (sock, token, via_accept, our_addr, peer_addr, commenced_at) = match via { Via::Accept(sock, t, commenced_at) => { let our_addr = sock.local_addr()?; let peer_addr = sock.peer_addr()?; (sock, t, true, our_addr, peer_addr, commenced_at) } Via::Connect { our_addr, peer_addr, } => { let stream = new_reusably_bound_tcp_sockets(&our_addr, 1)?.0[0].to_tcp_stream()?; stream.set_linger(Some(Duration::from_secs(0)))?; let sock = TcpSock::wrap(TcpStream::connect_stream(stream, &peer_addr)?); ( sock, ifc.new_token(), false, our_addr, peer_addr, Instant::now(), ) } }; poll.register( &sock, token, Ready::readable() | Ready::writable(), PollOpt::edge(), )?; let key = box_::precompute(peer_enc_pk, ifc.enc_sk()); let chooser = if ifc.enc_pk() > peer_enc_pk { ConnectionChooser::Choose(Some(::msg_to_send(CHOOSE_CONN, &key)?)) } else { ConnectionChooser::Wait(key) }; let puncher = Rc::new(RefCell::new(Puncher { token, sock, our_addr, peer_addr, via_accept, connection_chooser: chooser, timeout: None, commenced_at, f, })); if let Err((nat_state, e)) = ifc.insert_state(token, puncher) { debug!("Error inserting state: {:?}", e); nat_state.borrow_mut().terminate(ifc, poll); return Err(NatError::TcpHolePunchFailed); } Ok(token) } fn read(&mut self, ifc: &mut Interface, poll: &Poll) { let mut ok = false; loop { match self.sock.read::<Vec<u8>>() { Ok(Some(cipher_text)) => { if let ConnectionChooser::Wait(ref key) = self.connection_chooser { match ::
: {:?}", e); ok = false; break; } } } if ok { self.done(ifc, poll) } else { self.handle_err(ifc, poll) } } fn write(&mut self, ifc: &mut Interface, poll: &Poll, m: Option<Vec<u8>>) { match self.sock.write(m.map(|m| (m, 0))) { Ok(true) => self.done(ifc, poll), Ok(false) => (), Err(e) => { debug!("Tcp Puncher errored out in write: {:?}", e); self.handle_err(ifc, poll); } } } fn done(&mut self, ifc: &mut Interface, poll: &Poll) { if let Some(t) = self.timeout.take() { let _ = ifc.cancel_timeout(&t); } let _ = ifc.remove_state(self.token); let sock = mem::replace(&mut self.sock, Default::default()); let dur = self.commenced_at.elapsed(); (*self.f)(ifc, poll, self.token, Ok((sock, dur))); } fn handle_err(&mut self, ifc: &mut Interface, poll: &Poll) { if self.via_accept { self.terminate(ifc, poll); (*self.f)(ifc, poll, self.token, Err(NatError::TcpHolePunchFailed)); } else { let _ = poll.deregister(&self.sock); let _ = mem::replace(&mut self.sock, Default::default()); if let Some(t) = self.timeout.take() { let _ = ifc.cancel_timeout(&t); } match ifc.set_timeout( Duration::from_millis(RE_CONNECT_MS), NatTimer::new(self.token, TIMER_ID), ) { Ok(t) => self.timeout = Some(t), Err(e) => { debug!("Error setting timeout: {:?}", e); self.terminate(ifc, poll); (*self.f)(ifc, poll, self.token, Err(NatError::TcpHolePunchFailed)); } } } } } impl NatState for Puncher { fn ready(&mut self, ifc: &mut Interface, poll: &Poll, event: Ready) { if event.is_readable() { self.read(ifc, poll) } else if event.is_writable() { if !self.via_accept { let r = || -> ::Res<TcpSock> { let sock = mem::replace(&mut self.sock, Default::default()); sock.set_linger(None)?; Ok(sock) }(); match r { Ok(s) => self.sock = s, Err(e) => { debug!("Terminating due to error: {:?}", e); self.terminate(ifc, poll); (*self.f)(ifc, poll, self.token, Err(NatError::TcpHolePunchFailed)); } } } let m = if let ConnectionChooser::Choose(ref mut m) = self.connection_chooser { m.take() } else { return; }; self.write(ifc, poll, m) } else { warn!("Investigate: Ignoring unknown event kind: {:?}", event); } } fn timeout(&mut self, ifc: &mut Interface, poll: &Poll, timer_id: u8) { if timer_id != TIMER_ID { debug!("Invalid timer id: {}", timer_id); } let r = || -> ::Res<TcpSock> { let stream = new_reusably_bound_tcp_sockets(&self.our_addr, 1)?.0[0].to_tcp_stream()?; stream.set_linger(Some(Duration::from_secs(0)))?; let sock = TcpSock::wrap(TcpStream::connect_stream(stream, &self.peer_addr)?); poll.register( &sock, self.token, Ready::readable() | Ready::writable(), PollOpt::edge(), )?; Ok(sock) }(); match r { Ok(s) => self.sock = s, Err(e) => { debug!("Aborting connection attempt due to: {:?}", e); self.terminate(ifc, poll); (*self.f)(ifc, poll, self.token, Err(NatError::TcpHolePunchFailed)); } } } fn terminate(&mut self, ifc: &mut Interface, poll: &Poll) { if let Some(t) = self.timeout.take() { let _ = ifc.cancel_timeout(&t); } let _ = ifc.remove_state(self.token); let _ = poll.deregister(&self.sock); } fn as_any(&mut self) -> &mut Any { self } }
msg_to_read(&cipher_text, key) { Ok(ref plain_text) if plain_text == &CHOOSE_CONN => ok = true, _ => { debug!("Error: Failed to decrypt a connection-choose order"); ok = false; break; } } } else { debug!("Error: A chooser TcpPucher got a choose order"); ok = false; break; } } Ok(None) => { if ok { break; } else { return; } } Err(e) => { debug!("Tcp Puncher errored out in read
function_block-random_span
[ { "content": "/// Utility function to decrypt messages from peer\n\npub fn msg_to_read(raw: &[u8], key: &box_::PrecomputedKey) -> ::Res<Vec<u8>> {\n\n let CryptMsg { nonce, cipher_text } = deserialize(raw)?;\n\n box_::open_precomputed(&cipher_text, &box_::Nonce(nonce), key)\n\n .map_err(|()| NatErr...
Rust
santa/src/music.rs
BruceBrown/abstreet
3071dece5b0f95f887841a39c3d1aeb94bfdd9dd
use std::io::Cursor; use anyhow::Result; use rodio::{Decoder, OutputStream, OutputStreamHandle, Sink}; use widgetry::{ Checkbox, EventCtx, GfxCtx, HorizontalAlignment, Outcome, Panel, StyledButtons, VerticalAlignment, }; pub const OUT_OF_GAME: f32 = 0.5; pub const IN_GAME: f32 = 1.0; pub struct Music { inner: Option<Inner>, } impl std::default::Default for Music { fn default() -> Music { Music::empty() } } struct Inner { _stream: OutputStream, stream_handle: OutputStreamHandle, sink: Sink, unmuted_volume: f32, current_song: String, panel: Panel, } impl Music { pub fn empty() -> Music { Music { inner: None } } pub fn start(ctx: &mut EventCtx, play_music: bool, song: &str) -> Music { match Inner::new(ctx, play_music, song) { Ok(inner) => Music { inner: Some(inner) }, Err(err) => { error!("No music, sorry: {}", err); Music::empty() } } } pub fn event(&mut self, ctx: &mut EventCtx, play_music: &mut bool) { if let Some(ref mut inner) = self.inner { match inner.panel.event(ctx) { Outcome::Clicked(_) => unreachable!(), Outcome::Changed => { if inner.panel.is_checked("play music") { *play_music = true; inner.unmute(); } else { *play_music = false; inner.mute(); } } _ => {} } } } pub fn draw(&self, g: &mut GfxCtx) { if let Some(ref inner) = self.inner { inner.panel.draw(g); } } pub fn specify_volume(&mut self, volume: f32) { if let Some(ref mut inner) = self.inner { inner.specify_volume(volume); } } pub fn change_song(&mut self, song: &str) { if let Some(ref mut inner) = self.inner { if let Err(err) = inner.change_song(song) { warn!("Couldn't play {}: {}", song, err); } } } } impl Inner { fn new(ctx: &mut EventCtx, play_music: bool, song: &str) -> Result<Inner> { if cfg!(windows) { bail!("Audio disabled on Windows: https://github.com/a-b-street/abstreet/issues/430"); } let (stream, stream_handle) = OutputStream::try_default()?; let sink = rodio::Sink::try_new(&stream_handle)?; let raw_bytes = Cursor::new(abstio::slurp_file(abstio::path(format!( "system/assets/music/{}.ogg", song )))?); sink.append(Decoder::new_looped(raw_bytes)?); if !play_music { sink.set_volume(0.0); } let panel = Panel::new( Checkbox::new( play_music, ctx.style() .btn_solid_light_icon("system/assets/tools/volume_off.svg") .build(ctx, "play music"), ctx.style() .btn_solid_light_icon("system/assets/tools/volume_on.svg") .build(ctx, "mute music"), ) .named("play music") .container(), ) .aligned( HorizontalAlignment::LeftInset, VerticalAlignment::BottomInset, ) .build(ctx); Ok(Inner { _stream: stream, stream_handle, sink, unmuted_volume: 1.0, current_song: song.to_string(), panel, }) } fn unmute(&mut self) { self.sink.set_volume(self.unmuted_volume); } fn mute(&mut self) { self.sink.set_volume(0.0); } fn specify_volume(&mut self, volume: f32) { self.unmuted_volume = volume; if self.sink.volume() != 0.0 { self.unmute(); } } fn change_song(&mut self, song: &str) -> Result<()> { if self.current_song == song { return Ok(()); } self.current_song = song.to_string(); let old_volume = self.sink.volume(); self.sink = rodio::Sink::try_new(&self.stream_handle)?; let raw_bytes = Cursor::new(abstio::slurp_file(abstio::path(format!( "system/assets/music/{}.ogg", song )))?); self.sink.append(Decoder::new_looped(raw_bytes)?); self.sink.set_volume(old_volume); Ok(()) } }
use std::io::Cursor; use anyhow::Result; use rodio::{Decoder, OutputStream, OutputStreamHandle, Sink}; use widgetry::{ Checkbox, EventCtx, GfxCtx, HorizontalAlignment, Outcome, Panel, StyledButtons, VerticalAlignment, }; pub const OUT_OF_GAME: f32 = 0.5; pub const IN_GAME: f32 = 1.0; pub struct Music { inner: Option<Inner>, } impl std::default::Default for Music { fn default() -> Music { Music::empty() } } struct Inner { _stream: OutputStream, stream_handle: OutputStreamHandle, sink: Sink, unmuted_volume: f32, current_song: String, panel: Panel, } impl Music { pub fn empty() -> Music { Music { inner: None } } pub fn start(ctx: &mut EventCtx, play_music: bool, song: &str) -> Music { match Inner::new(ctx, play_music, song) { Ok(inner) => Music { inner: Some(inner) }, Err(err) => { error!("No music, sorry: {}", err); Music::empty() } } } pub fn event(&mut self, ctx: &mut EventCtx, play_music: &mut bool) { if let Some(ref mut inner) = self.inner { match inner.panel.event(ctx) { Outcome::Clicked(_) => unreachable!(), Outcome::Changed => { if inner.panel.is
} fn unmute(&mut self) { self.sink.set_volume(self.unmuted_volume); } fn mute(&mut self) { self.sink.set_volume(0.0); } fn specify_volume(&mut self, volume: f32) { self.unmuted_volume = volume; if self.sink.volume() != 0.0 { self.unmute(); } } fn change_song(&mut self, song: &str) -> Result<()> { if self.current_song == song { return Ok(()); } self.current_song = song.to_string(); let old_volume = self.sink.volume(); self.sink = rodio::Sink::try_new(&self.stream_handle)?; let raw_bytes = Cursor::new(abstio::slurp_file(abstio::path(format!( "system/assets/music/{}.ogg", song )))?); self.sink.append(Decoder::new_looped(raw_bytes)?); self.sink.set_volume(old_volume); Ok(()) } }
_checked("play music") { *play_music = true; inner.unmute(); } else { *play_music = false; inner.mute(); } } _ => {} } } } pub fn draw(&self, g: &mut GfxCtx) { if let Some(ref inner) = self.inner { inner.panel.draw(g); } } pub fn specify_volume(&mut self, volume: f32) { if let Some(ref mut inner) = self.inner { inner.specify_volume(volume); } } pub fn change_song(&mut self, song: &str) { if let Some(ref mut inner) = self.inner { if let Err(err) = inner.change_song(song) { warn!("Couldn't play {}: {}", song, err); } } } } impl Inner { fn new(ctx: &mut EventCtx, play_music: bool, song: &str) -> Result<Inner> { if cfg!(windows) { bail!("Audio disabled on Windows: https://github.com/a-b-street/abstreet/issues/430"); } let (stream, stream_handle) = OutputStream::try_default()?; let sink = rodio::Sink::try_new(&stream_handle)?; let raw_bytes = Cursor::new(abstio::slurp_file(abstio::path(format!( "system/assets/music/{}.ogg", song )))?); sink.append(Decoder::new_looped(raw_bytes)?); if !play_music { sink.set_volume(0.0); } let panel = Panel::new( Checkbox::new( play_music, ctx.style() .btn_solid_light_icon("system/assets/tools/volume_off.svg") .build(ctx, "play music"), ctx.style() .btn_solid_light_icon("system/assets/tools/volume_on.svg") .build(ctx, "mute music"), ) .named("play music") .container(), ) .aligned( HorizontalAlignment::LeftInset, VerticalAlignment::BottomInset, ) .build(ctx); Ok(Inner { _stream: stream, stream_handle, sink, unmuted_volume: 1.0, current_song: song.to_string(), panel, })
random
[ { "content": "// TODO Kinda misnomer\n\npub fn tool_panel(ctx: &mut EventCtx) -> Panel {\n\n Panel::new(Widget::row(vec![\n\n ctx.style()\n\n .btn_plain_light_icon(\"system/assets/tools/home.svg\")\n\n .hotkey(Key::Escape)\n\n .build_widget(ctx, \"back\"),\n\n c...
Rust
src/client/connect.rs
aturon/hyper
8c6e6f51abb0dd02123b8bfafa9277850623b810
use std::collections::hash_map::{HashMap, Entry}; use std::hash::Hash; use std::fmt; use std::io; use std::net::SocketAddr; use rotor::mio::tcp::TcpStream; use url::Url; use net::{HttpStream, HttpsStream, Transport, SslClient}; use super::dns::Dns; use super::Registration; pub trait Connect { type Output: Transport; type Key: Eq + Hash + Clone + fmt::Debug; fn key(&self, &Url) -> Option<Self::Key>; fn connect(&mut self, &Url) -> io::Result<Self::Key>; fn connected(&mut self) -> Option<(Self::Key, io::Result<Self::Output>)>; #[doc(hidden)] fn register(&mut self, Registration); } type Scheme = String; type Port = u16; pub struct HttpConnector { dns: Option<Dns>, threads: usize, resolving: HashMap<String, Vec<(&'static str, String, u16)>>, } impl HttpConnector { pub fn threads(mut self, threads: usize) -> HttpConnector { debug_assert!(self.dns.is_none(), "setting threads after Dns is created does nothing"); self.threads = threads; self } } impl Default for HttpConnector { fn default() -> HttpConnector { HttpConnector { dns: None, threads: 4, resolving: HashMap::new(), } } } impl fmt::Debug for HttpConnector { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("HttpConnector") .field("threads", &self.threads) .field("resolving", &self.resolving) .finish() } } impl Connect for HttpConnector { type Output = HttpStream; type Key = (&'static str, String, u16); fn key(&self, url: &Url) -> Option<Self::Key> { if url.scheme() == "http" { Some(( "http", url.host_str().expect("http scheme must have host").to_owned(), url.port().unwrap_or(80), )) } else { None } } fn connect(&mut self, url: &Url) -> io::Result<Self::Key> { debug!("Http::connect({:?})", url); if let Some(key) = self.key(url) { let host = url.host_str().expect("http scheme must have a host"); self.dns.as_ref().expect("dns workers lost").resolve(host); self.resolving.entry(host.to_owned()).or_insert_with(Vec::new).push(key.clone()); Ok(key) } else { Err(io::Error::new(io::ErrorKind::InvalidInput, "scheme must be http")) } } fn connected(&mut self) -> Option<(Self::Key, io::Result<HttpStream>)> { let (host, addrs) = match self.dns.as_ref().expect("dns workers lost").resolved() { Ok(res) => res, Err(_) => return None }; let addr = addrs.and_then(|mut addrs| Ok(addrs.next().unwrap())); debug!("Http::resolved <- ({:?}, {:?})", host, addr); if let Entry::Occupied(mut entry) = self.resolving.entry(host) { let resolved = entry.get_mut().remove(0); if entry.get().is_empty() { entry.remove(); } let port = resolved.2; Some((resolved, addr.and_then(|addr| TcpStream::connect(&SocketAddr::new(addr, port)) .map(HttpStream)) )) } else { trace!("^-- resolved but not in hashmap?"); None } } fn register(&mut self, reg: Registration) { self.dns = Some(Dns::new(reg.notify, 4)); } } #[derive(Debug, Default)] pub struct HttpsConnector<S: SslClient> { http: HttpConnector, ssl: S } impl<S: SslClient> HttpsConnector<S> { pub fn new(s: S) -> HttpsConnector<S> { HttpsConnector { http: HttpConnector::default(), ssl: s, } } } impl<S: SslClient> Connect for HttpsConnector<S> { type Output = HttpsStream<S::Stream>; type Key = (&'static str, String, u16); fn key(&self, url: &Url) -> Option<Self::Key> { let scheme = match url.scheme() { "http" => "http", "https" => "https", _ => return None }; Some(( scheme, url.host_str().expect("http scheme must have host").to_owned(), url.port_or_known_default().expect("http scheme must have a port"), )) } fn connect(&mut self, url: &Url) -> io::Result<Self::Key> { debug!("Https::connect({:?})", url); if let Some(key) = self.key(url) { let host = url.host_str().expect("http scheme must have a host"); self.http.dns.as_ref().expect("dns workers lost").resolve(host); self.http.resolving.entry(host.to_owned()).or_insert_with(Vec::new).push(key.clone()); Ok(key) } else { Err(io::Error::new(io::ErrorKind::InvalidInput, "scheme must be http or https")) } } fn connected(&mut self) -> Option<(Self::Key, io::Result<Self::Output>)> { self.http.connected().map(|(key, res)| { let res = res.and_then(|http| { if key.0 == "https" { self.ssl.wrap_client(http, &key.1) .map(HttpsStream::Https) .map_err(|e| match e { ::Error::Io(e) => e, e => io::Error::new(io::ErrorKind::Other, e) }) } else { Ok(HttpsStream::Http(http)) } }); (key, res) }) } fn register(&mut self, reg: Registration) { self.http.register(reg); } } #[cfg(not(any(feature = "openssl", feature = "security-framework")))] #[doc(hidden)] pub type DefaultConnector = HttpConnector; #[cfg(all(feature = "openssl", not(feature = "security-framework")))] #[doc(hidden)] pub type DefaultConnector = HttpsConnector<::net::Openssl>; #[cfg(feature = "security-framework")] #[doc(hidden)] pub type DefaultConnector = HttpsConnector<::net::SecureTransportClient>; #[doc(hidden)] pub type DefaultTransport = <DefaultConnector as Connect>::Output; fn _assert_defaults() { fn _assert<T, U>() where T: Connect<Output=U>, U: Transport {} _assert::<DefaultConnector, DefaultTransport>(); }
use std::collections::hash_map::{HashMap, Entry}; use std::hash::Hash; use std::fmt; use std::io; use std::net::SocketAddr; use rotor::mio::tcp::TcpStream; use url::Url; use net::{HttpStream, HttpsStream, Transport, SslClient}; use super::dns::Dns; use super::Registration; pub trait Connect { type Output: Transport; type Key: Eq + Hash + Clone + fmt::Debug; fn key(&self, &Url) -> Option<Self::Key>; fn connect(&mut self, &Url) -> io::Result<Self::Key>; fn connected(&mut self) -> Option<(Self::Key, io::Result<Self::Output>)>; #[doc(hidden)] fn register(&mut self, Registration); } type Scheme = String; type Port = u16; pub struct HttpConnector { dns: Option<Dns>, threads: usize, resolving: HashMap<String, Vec<(&'static str, String, u16)>>, } impl HttpConnector { pub fn threads(mut self, threads: usize) -> HttpConnector { debug_assert!(self.dns.is_none(), "setting threads after Dns is created does nothing"); self.threads = threads; self } } impl Default for HttpConnector { fn default() -> HttpConnector { HttpConnector { dns: None, threads: 4, resolving: HashMap::new(), } } } impl fmt::Debug for HttpConnector { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("HttpConnector") .field("threads", &self.threads) .field("resolving", &self.resolving) .finish() } } impl Connect for HttpConnector { type Output = HttpStream; type Key = (&'static str, String, u16); fn key(&self, url: &Url) -> Option<Self::Key> { if url.scheme() == "http" { Some(( "http", url.host_str().expect("http scheme must have host").to_owned(), url.port().unwrap_or(80), )) } else { None } } fn connect(&mut self, url: &Url) -> io::Result<Self::Key> { debug!("Http::connect({:?})", url); if let Some(key) = self.key(url) { let host = url.host_str().expect("http scheme must have a host"); self.dns.as_ref().expect("dns workers lost").resolve(host); self.resolving.entry(host.to_owned()).or_insert_with(Vec::new).push(key.clone()); Ok(key) } else { Err(io::Error::new(io::ErrorKind::InvalidInput, "scheme must be http")) } } fn connected(&mut self) -> Option<(Self::Key, io::Result<HttpStream>)> { let (host, addrs) = match self.dns.as_ref().expect("dns workers lost").resolved() { Ok(res) => res, Err(_) => return None }; let addr = addrs.and_then(|mut addrs| Ok(addrs.next().unwrap())); debug!("Http::resolved <- ({:?}, {:?})", host, addr); if let Entry::Occupied(mut entry) = self.resolving.entry(host) { let resolved = entry.get_mut().remove(0); if entry.get().is_empty() { entry.remove(); } let port = resolved.2; Some((resolved, addr.and_then(|addr| TcpStream::connect(&SocketAddr::new(addr, port)) .map(HttpStream)) )) } else { trace!("^-- resolved but not in hashmap?"); None } } fn register(&mut self, reg: Registration) { self.dns = Some(Dns::new(reg.notify, 4)); } } #[derive(Debug, Default)] pub struct HttpsConnector<S: SslClient> { http: HttpConnector, ssl: S } impl<S: SslClient> HttpsConnector<S> { pub fn new(s: S) -> HttpsConnector<S> { HttpsConnector { http: HttpConnector::default(), ssl: s, } } } impl<S: SslClient> Connect for HttpsConnector<S> { type Output = HttpsStream<S::Stream>; type Key = (&'static str, String, u16); fn key(&self, url: &Url) -> Option<Self::Key> { let scheme = match url.scheme() { "http" => "http", "https" => "https", _ => return None }; Some(( schem
fn connect(&mut self, url: &Url) -> io::Result<Self::Key> { debug!("Https::connect({:?})", url); if let Some(key) = self.key(url) { let host = url.host_str().expect("http scheme must have a host"); self.http.dns.as_ref().expect("dns workers lost").resolve(host); self.http.resolving.entry(host.to_owned()).or_insert_with(Vec::new).push(key.clone()); Ok(key) } else { Err(io::Error::new(io::ErrorKind::InvalidInput, "scheme must be http or https")) } } fn connected(&mut self) -> Option<(Self::Key, io::Result<Self::Output>)> { self.http.connected().map(|(key, res)| { let res = res.and_then(|http| { if key.0 == "https" { self.ssl.wrap_client(http, &key.1) .map(HttpsStream::Https) .map_err(|e| match e { ::Error::Io(e) => e, e => io::Error::new(io::ErrorKind::Other, e) }) } else { Ok(HttpsStream::Http(http)) } }); (key, res) }) } fn register(&mut self, reg: Registration) { self.http.register(reg); } } #[cfg(not(any(feature = "openssl", feature = "security-framework")))] #[doc(hidden)] pub type DefaultConnector = HttpConnector; #[cfg(all(feature = "openssl", not(feature = "security-framework")))] #[doc(hidden)] pub type DefaultConnector = HttpsConnector<::net::Openssl>; #[cfg(feature = "security-framework")] #[doc(hidden)] pub type DefaultConnector = HttpsConnector<::net::SecureTransportClient>; #[doc(hidden)] pub type DefaultTransport = <DefaultConnector as Connect>::Output; fn _assert_defaults() { fn _assert<T, U>() where T: Connect<Output=U>, U: Transport {} _assert::<DefaultConnector, DefaultTransport>(); }
e, url.host_str().expect("http scheme must have host").to_owned(), url.port_or_known_default().expect("http scheme must have a port"), )) }
function_block-function_prefixed
[ { "content": "pub trait Key: Eq + Hash + Clone + fmt::Debug {}\n\nimpl<T: Eq + Hash + Clone + fmt::Debug> Key for T {}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n /* TODO:\n\n test when the underlying Transport of a Conn is blocked on an action that\n\n differs from the desired interest().\n\n\n\n Ex:\n\...
Rust
src/multihash.rs
woss/rust-multihash
3e5c8392960762588c62508fcf7bb2d71a1a1d1a
use crate::Error; #[cfg(feature = "alloc")] use alloc::vec::Vec; use core::convert::TryFrom; use core::convert::TryInto; use core::fmt::Debug; #[cfg(feature = "serde-codec")] use serde_big_array::BigArray; use unsigned_varint::encode as varint_encode; #[cfg(feature = "std")] use std::io; #[cfg(not(feature = "std"))] use core2::io; pub trait MultihashDigest<const S: usize>: TryFrom<u64> + Into<u64> + Send + Sync + Unpin + Copy + Eq + Debug + 'static { fn digest(&self, input: &[u8]) -> Multihash<S>; fn wrap(&self, digest: &[u8]) -> Result<Multihash<S>, Error>; } #[cfg_attr(feature = "serde-codec", derive(serde::Deserialize))] #[cfg_attr(feature = "serde-codec", derive(serde::Serialize))] #[derive(Clone, Copy, Debug, Eq, Ord, PartialOrd)] pub struct Multihash<const S: usize> { code: u64, size: u8, #[cfg_attr(feature = "serde-codec", serde(with = "BigArray"))] digest: [u8; S], } impl<const S: usize> Default for Multihash<S> { fn default() -> Self { Self { code: 0, size: 0, digest: [0; S], } } } impl<const S: usize> Multihash<S> { pub const fn wrap(code: u64, input_digest: &[u8]) -> Result<Self, Error> { if input_digest.len() > S { return Err(Error::InvalidSize(input_digest.len() as _)); } let size = input_digest.len(); let mut digest = [0; S]; let mut i = 0; while i < size { digest[i] = input_digest[i]; i += 1; } Ok(Self { code, size: size as u8, digest, }) } pub const fn code(&self) -> u64 { self.code } pub const fn size(&self) -> u8 { self.size } pub fn digest(&self) -> &[u8] { &self.digest[..self.size as usize] } pub fn read<R: io::Read>(r: R) -> Result<Self, Error> where Self: Sized, { let (code, size, digest) = read_multihash(r)?; Ok(Self { code, size, digest }) } pub fn from_bytes(mut bytes: &[u8]) -> Result<Self, Error> where Self: Sized, { let result = Self::read(&mut bytes)?; if !bytes.is_empty() { return Err(Error::InvalidSize(bytes.len().try_into().expect( "Currently the maximum size is 255, therefore always fits into usize", ))); } Ok(result) } pub fn write<W: io::Write>(&self, w: W) -> Result<(), Error> { write_multihash(w, self.code(), self.size(), self.digest()) } #[cfg(feature = "alloc")] pub fn to_bytes(&self) -> Vec<u8> { let mut bytes = Vec::with_capacity(self.size().into()); self.write(&mut bytes) .expect("writing to a vec should never fail"); bytes } pub fn truncate(&self, size: u8) -> Self { let mut mh = *self; mh.size = mh.size.min(size); mh } pub fn resize<const R: usize>(&self) -> Result<Multihash<R>, Error> { let size = self.size as usize; if size > R { return Err(Error::InvalidSize(self.size as u64)); } let mut mh = Multihash { code: self.code, size: self.size, digest: [0; R], }; mh.digest[..size].copy_from_slice(&self.digest[..size]); Ok(mh) } } #[allow(clippy::derive_hash_xor_eq)] impl<const S: usize> core::hash::Hash for Multihash<S> { fn hash<T: core::hash::Hasher>(&self, state: &mut T) { self.code.hash(state); self.digest().hash(state); } } #[cfg(feature = "alloc")] impl<const S: usize> From<Multihash<S>> for Vec<u8> { fn from(multihash: Multihash<S>) -> Self { multihash.to_bytes() } } impl<const A: usize, const B: usize> PartialEq<Multihash<B>> for Multihash<A> { fn eq(&self, other: &Multihash<B>) -> bool { self.code == other.code && self.digest() == other.digest() } } #[cfg(feature = "scale-codec")] impl<const S: usize> parity_scale_codec::Encode for Multihash<S> { fn encode_to<EncOut: parity_scale_codec::Output + ?Sized>(&self, dest: &mut EncOut) { self.code.encode_to(dest); self.size.encode_to(dest); dest.write(self.digest()); } } #[cfg(feature = "scale-codec")] impl<const S: usize> parity_scale_codec::EncodeLike for Multihash<S> {} #[cfg(feature = "scale-codec")] impl<const S: usize> parity_scale_codec::Decode for Multihash<S> { fn decode<DecIn: parity_scale_codec::Input>( input: &mut DecIn, ) -> Result<Self, parity_scale_codec::Error> { let mut mh = Multihash { code: parity_scale_codec::Decode::decode(input)?, size: parity_scale_codec::Decode::decode(input)?, digest: [0; S], }; if mh.size as usize > S { return Err(parity_scale_codec::Error::from("invalid size")); } input.read(&mut mh.digest[..mh.size as usize])?; Ok(mh) } } pub fn write_multihash<W>(mut w: W, code: u64, size: u8, digest: &[u8]) -> Result<(), Error> where W: io::Write, { let mut code_buf = varint_encode::u64_buffer(); let code = varint_encode::u64(code, &mut code_buf); let mut size_buf = varint_encode::u8_buffer(); let size = varint_encode::u8(size, &mut size_buf); w.write_all(code)?; w.write_all(size)?; w.write_all(digest)?; Ok(()) } pub fn read_multihash<R, const S: usize>(mut r: R) -> Result<(u64, u8, [u8; S]), Error> where R: io::Read, { let code = read_u64(&mut r)?; let size = read_u64(&mut r)?; if size > S as u64 || size > u8::MAX as u64 { return Err(Error::InvalidSize(size)); } let mut digest = [0; S]; r.read_exact(&mut digest[..size as usize])?; Ok((code, size as u8, digest)) } #[cfg(feature = "std")] pub(crate) use unsigned_varint::io::read_u64; #[cfg(not(feature = "std"))] pub(crate) fn read_u64<R: io::Read>(mut r: R) -> Result<u64, Error> { use unsigned_varint::decode; let mut b = varint_encode::u64_buffer(); for i in 0..b.len() { let n = r.read(&mut (b[i..i + 1]))?; if n == 0 { return Err(Error::Varint(decode::Error::Insufficient)); } else if decode::is_last(b[i]) { return Ok(decode::u64(&b[..=i]).unwrap().0); } } Err(Error::Varint(decode::Error::Overflow)) } #[cfg(test)] mod tests { use super::*; use crate::multihash_impl::Code; #[test] fn roundtrip() { let hash = Code::Sha2_256.digest(b"hello world"); let mut buf = [0u8; 35]; hash.write(&mut buf[..]).unwrap(); let hash2 = Multihash::<32>::read(&buf[..]).unwrap(); assert_eq!(hash, hash2); } #[test] fn test_truncate_down() { let hash = Code::Sha2_256.digest(b"hello world"); let small = hash.truncate(20); assert_eq!(small.size(), 20); } #[test] fn test_truncate_up() { let hash = Code::Sha2_256.digest(b"hello world"); let small = hash.truncate(100); assert_eq!(small.size(), 32); } #[test] fn test_resize_fits() { let hash = Code::Sha2_256.digest(b"hello world"); let _: Multihash<32> = hash.resize().unwrap(); } #[test] fn test_resize_up() { let hash = Code::Sha2_256.digest(b"hello world"); let _: Multihash<100> = hash.resize().unwrap(); } #[test] fn test_resize_truncate() { let hash = Code::Sha2_256.digest(b"hello world"); hash.resize::<20>().unwrap_err(); } #[test] #[cfg(feature = "scale-codec")] fn test_scale() { use parity_scale_codec::{Decode, Encode}; let mh1 = Code::Sha2_256.digest(b"hello world"); let mh1_bytes = mh1.encode(); let mh2: Multihash<32> = Decode::decode(&mut &mh1_bytes[..]).unwrap(); assert_eq!(mh1, mh2); let mh3: Multihash<64> = Code::Sha2_256.digest(b"hello world"); let mh3_bytes = mh3.encode(); let mh4: Multihash<64> = Decode::decode(&mut &mh3_bytes[..]).unwrap(); assert_eq!(mh3, mh4); assert_eq!(mh1_bytes, mh3_bytes); } #[test] #[cfg(feature = "serde-codec")] fn test_serde() { let mh = Multihash::<32>::default(); let bytes = serde_json::to_string(&mh).unwrap(); let mh2: Multihash<32> = serde_json::from_str(&bytes).unwrap(); assert_eq!(mh, mh2); } #[test] fn test_eq_sizes() { let mh1 = Multihash::<32>::default(); let mh2 = Multihash::<64>::default(); assert_eq!(mh1, mh2); } }
use crate::Error; #[cfg(feature = "alloc")] use alloc::vec::Vec; use core::convert::TryFrom; use core::convert::TryInto; use core::fmt::Debug; #[cfg(feature = "serde-codec")] use serde_big_array::BigArray; use unsigned_varint::encode as varint_encode; #[cfg(feature = "std")] use std::io; #[cfg(not(feature = "std"))] use core2::io; pub trait MultihashDigest<const S: usize>: TryFrom<u64> + Into<u64> + Send + Sync + Unpin + Copy + Eq + Debug + 'static { fn digest(&self, input: &[u8]) -> Multihash<S>; fn wrap(&self, digest: &[u8]) -> Result<Multihash<S>, Error>; } #[cfg_attr(feature = "serde-codec", derive(serde::Deserialize))] #[cfg_attr(feature = "serde-codec", derive(serde::Serialize))] #[derive(Clone, Copy, Debug, Eq, Ord, PartialOrd)] pub struct Multihash<const S: usize> { code: u64, size: u8, #[cfg_attr(feature = "serde-codec", serde(with = "BigArray"))] digest: [u8; S], } impl<const S: usize> Default for Multihash<S> { fn default() -> Self { Self { code: 0, size: 0, digest: [0; S], } } } impl<const S: usize> Multihash<S> { pub const fn wrap(code: u64, input_digest: &[u8]) -> Result<Self, Error> { if input_digest.len() > S { return Err(Error::InvalidSize(input_digest.len() as _)); } let size = input_digest.len(); let mut digest = [0; S]; let mut i = 0; while i < size { digest[i] = input_digest[i]; i += 1; } Ok(Self { code, size: size as u8, digest, }) } pub const fn code(&self) -> u64 { self.code } pub const fn size(&self) -> u8 { self.size } pub fn digest(&self) -> &[u8] { &self.digest[..self.size as usize] } pub fn read<R: io::Read>(r: R) -> Result<Self, Error> where Self: Sized, { let (code, size, digest) = read_multihash(r)?; Ok(Self { code, size, digest }) } pub fn from_bytes(mut bytes: &[u8]) -> Result<Self, Error> where Self: Sized, { let result = Self::read(&mut bytes)?; if !bytes.is_empty() { return Err(Error::InvalidSize(bytes.len().try_into().expect( "Currently the maximum size is 255, therefore always fits into usize", ))); } Ok(result) } pub fn write<W: io::Write>(&self, w: W) -> Result<(), Error> { write_multihash(w, self.code(), self.size(), self.digest()) } #[cfg(feature = "alloc")] pub fn to_bytes(&self) -> Vec<u8> { let
ad_exact(&mut digest[..size as usize])?; Ok((code, size as u8, digest)) } #[cfg(feature = "std")] pub(crate) use unsigned_varint::io::read_u64; #[cfg(not(feature = "std"))] pub(crate) fn read_u64<R: io::Read>(mut r: R) -> Result<u64, Error> { use unsigned_varint::decode; let mut b = varint_encode::u64_buffer(); for i in 0..b.len() { let n = r.read(&mut (b[i..i + 1]))?; if n == 0 { return Err(Error::Varint(decode::Error::Insufficient)); } else if decode::is_last(b[i]) { return Ok(decode::u64(&b[..=i]).unwrap().0); } } Err(Error::Varint(decode::Error::Overflow)) } #[cfg(test)] mod tests { use super::*; use crate::multihash_impl::Code; #[test] fn roundtrip() { let hash = Code::Sha2_256.digest(b"hello world"); let mut buf = [0u8; 35]; hash.write(&mut buf[..]).unwrap(); let hash2 = Multihash::<32>::read(&buf[..]).unwrap(); assert_eq!(hash, hash2); } #[test] fn test_truncate_down() { let hash = Code::Sha2_256.digest(b"hello world"); let small = hash.truncate(20); assert_eq!(small.size(), 20); } #[test] fn test_truncate_up() { let hash = Code::Sha2_256.digest(b"hello world"); let small = hash.truncate(100); assert_eq!(small.size(), 32); } #[test] fn test_resize_fits() { let hash = Code::Sha2_256.digest(b"hello world"); let _: Multihash<32> = hash.resize().unwrap(); } #[test] fn test_resize_up() { let hash = Code::Sha2_256.digest(b"hello world"); let _: Multihash<100> = hash.resize().unwrap(); } #[test] fn test_resize_truncate() { let hash = Code::Sha2_256.digest(b"hello world"); hash.resize::<20>().unwrap_err(); } #[test] #[cfg(feature = "scale-codec")] fn test_scale() { use parity_scale_codec::{Decode, Encode}; let mh1 = Code::Sha2_256.digest(b"hello world"); let mh1_bytes = mh1.encode(); let mh2: Multihash<32> = Decode::decode(&mut &mh1_bytes[..]).unwrap(); assert_eq!(mh1, mh2); let mh3: Multihash<64> = Code::Sha2_256.digest(b"hello world"); let mh3_bytes = mh3.encode(); let mh4: Multihash<64> = Decode::decode(&mut &mh3_bytes[..]).unwrap(); assert_eq!(mh3, mh4); assert_eq!(mh1_bytes, mh3_bytes); } #[test] #[cfg(feature = "serde-codec")] fn test_serde() { let mh = Multihash::<32>::default(); let bytes = serde_json::to_string(&mh).unwrap(); let mh2: Multihash<32> = serde_json::from_str(&bytes).unwrap(); assert_eq!(mh, mh2); } #[test] fn test_eq_sizes() { let mh1 = Multihash::<32>::default(); let mh2 = Multihash::<64>::default(); assert_eq!(mh1, mh2); } }
mut bytes = Vec::with_capacity(self.size().into()); self.write(&mut bytes) .expect("writing to a vec should never fail"); bytes } pub fn truncate(&self, size: u8) -> Self { let mut mh = *self; mh.size = mh.size.min(size); mh } pub fn resize<const R: usize>(&self) -> Result<Multihash<R>, Error> { let size = self.size as usize; if size > R { return Err(Error::InvalidSize(self.size as u64)); } let mut mh = Multihash { code: self.code, size: self.size, digest: [0; R], }; mh.digest[..size].copy_from_slice(&self.digest[..size]); Ok(mh) } } #[allow(clippy::derive_hash_xor_eq)] impl<const S: usize> core::hash::Hash for Multihash<S> { fn hash<T: core::hash::Hasher>(&self, state: &mut T) { self.code.hash(state); self.digest().hash(state); } } #[cfg(feature = "alloc")] impl<const S: usize> From<Multihash<S>> for Vec<u8> { fn from(multihash: Multihash<S>) -> Self { multihash.to_bytes() } } impl<const A: usize, const B: usize> PartialEq<Multihash<B>> for Multihash<A> { fn eq(&self, other: &Multihash<B>) -> bool { self.code == other.code && self.digest() == other.digest() } } #[cfg(feature = "scale-codec")] impl<const S: usize> parity_scale_codec::Encode for Multihash<S> { fn encode_to<EncOut: parity_scale_codec::Output + ?Sized>(&self, dest: &mut EncOut) { self.code.encode_to(dest); self.size.encode_to(dest); dest.write(self.digest()); } } #[cfg(feature = "scale-codec")] impl<const S: usize> parity_scale_codec::EncodeLike for Multihash<S> {} #[cfg(feature = "scale-codec")] impl<const S: usize> parity_scale_codec::Decode for Multihash<S> { fn decode<DecIn: parity_scale_codec::Input>( input: &mut DecIn, ) -> Result<Self, parity_scale_codec::Error> { let mut mh = Multihash { code: parity_scale_codec::Decode::decode(input)?, size: parity_scale_codec::Decode::decode(input)?, digest: [0; S], }; if mh.size as usize > S { return Err(parity_scale_codec::Error::from("invalid size")); } input.read(&mut mh.digest[..mh.size as usize])?; Ok(mh) } } pub fn write_multihash<W>(mut w: W, code: u64, size: u8, digest: &[u8]) -> Result<(), Error> where W: io::Write, { let mut code_buf = varint_encode::u64_buffer(); let code = varint_encode::u64(code, &mut code_buf); let mut size_buf = varint_encode::u8_buffer(); let size = varint_encode::u8(size, &mut size_buf); w.write_all(code)?; w.write_all(size)?; w.write_all(digest)?; Ok(()) } pub fn read_multihash<R, const S: usize>(mut r: R) -> Result<(u64, u8, [u8; S]), Error> where R: io::Read, { let code = read_u64(&mut r)?; let size = read_u64(&mut r)?; if size > S as u64 || size > u8::MAX as u64 { return Err(Error::InvalidSize(size)); } let mut digest = [0; S]; r.re
random
[ { "content": "pub fn use_crate(name: &str) -> Result<syn::Ident, Error> {\n\n match crate_name(name) {\n\n Ok(FoundCrate::Name(krate)) => Ok(syn::Ident::new(&krate, Span::call_site())),\n\n Ok(FoundCrate::Itself) => Ok(syn::Ident::new(\"crate\", Span::call_site())),\n\n Err(err) => Err(E...
Rust
examples/forest/src/main.rs
dbuch/three-d
8263eb240c98cff6dcfd6832c0c2572e4bf032e8
#[cfg(not(target_arch = "wasm32"))] #[tokio::main] async fn main() { run().await; } use three_d::*; pub async fn run() { let window = Window::new(WindowSettings { title: "Forest!".to_string(), max_size: Some((1280, 720)), ..Default::default() }) .unwrap(); let context = window.gl().unwrap(); let mut camera = Camera::new_perspective( &context, window.viewport().unwrap(), vec3(2800.0, 240.0, 1700.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), degrees(60.0), 0.1, 10000.0, ) .unwrap(); let mut control = FlyControl::new(0.1); let mut loaded = Loader::load_async(&[ "examples/assets/Gledista_Triacanthos.obj", "examples/assets/Gledista_Triacanthos.mtl", "examples/assets/maps/gleditsia_triacanthos_flowers_color.jpg", "examples/assets/maps/gleditsia_triacanthos_flowers_mask.jpg", "examples/assets/maps/gleditsia_triacanthos_bark_reflect.jpg", "examples/assets/maps/gleditsia_triacanthos_bark2_a1.jpg", "examples/assets/maps/gleditsia_triacanthos_leaf_color_b1.jpg", "examples/assets/maps/gleditsia_triacanthos_leaf_mask.jpg", ]) .await .unwrap(); let (mut meshes, materials) = loaded.obj(".obj").unwrap(); let mut models = Vec::new(); for mut mesh in meshes.drain(..) { mesh.compute_normals(); let mut model = Model::new_with_material( &context, &mesh, PhysicalMaterial::new( &context, &materials .iter() .find(|m| Some(&m.name) == mesh.material_name.as_ref()) .unwrap(), ) .unwrap(), ) .unwrap(); model.material.render_states.cull = Cull::Back; models.push(model); } let ambient = AmbientLight::new(&context, 0.3, Color::WHITE).unwrap(); let directional = DirectionalLight::new(&context, 4.0, Color::WHITE, &vec3(-1.0, -1.0, -1.0)).unwrap(); let mut aabb = AxisAlignedBoundingBox::EMPTY; models.iter().for_each(|m| { aabb.expand_with_aabb(&m.aabb()); }); let size = aabb.size(); let t = 100; let mut positions = Vec::new(); for x in -t..t + 1 { for y in -t..t + 1 { if x != 0 || y != 0 { positions.push(vec3(size.x * x as f32, 0.0, size.y * y as f32)); } } } let imposters = Imposters::new( &context, &positions, &models.iter().map(|m| m as &dyn Object).collect::<Vec<_>>(), &[&ambient, &directional], 256, ) .unwrap(); let mut plane = Model::new_with_material( &context, &CpuMesh { positions: Positions::F32(vec![ vec3(-10000.0, 0.0, 10000.0), vec3(10000.0, 0.0, 10000.0), vec3(0.0, 0.0, -10000.0), ]), normals: Some(vec![ vec3(0.0, 1.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 1.0, 0.0), ]), ..Default::default() }, PhysicalMaterial { albedo: Color::new_opaque(128, 200, 70), metallic: 0.0, roughness: 1.0, ..Default::default() }, ) .unwrap(); plane.material.render_states.cull = Cull::Back; models.push(plane); window .render_loop(move |mut frame_input| { let mut redraw = frame_input.first_frame; redraw |= camera.set_viewport(frame_input.viewport).unwrap(); redraw |= control .handle_events(&mut camera, &mut frame_input.events) .unwrap(); if redraw { let mut models = models.iter().map(|m| m as &dyn Object).collect::<Vec<_>>(); models.push(&imposters); frame_input .screen() .clear(ClearState::color_and_depth(0.8, 0.8, 0.8, 1.0, 1.0)) .unwrap() .render(&camera, &models, &[&ambient, &directional]) .unwrap(); } FrameOutput { swap_buffers: redraw, ..Default::default() } }) .unwrap(); }
#[cfg(not(target_arch = "wasm32"))] #[tokio::main] async fn main() { run().await; } use three_d::*; pub async fn run() { let window = Window::new(WindowSettings { title: "Forest!".to_string(), max_size: Some((1280, 720)), ..Default::default() }) .unwrap(); let context = window.gl().unwrap(); let mut camera = Camera::new_perspective( &context, window.viewport().unwrap(), vec3(2800.0, 240.0, 1700.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), degrees(60.0), 0.1, 10000.0, ) .unwrap(); let mut control = FlyControl::new(0.1); let mut loaded = Loader::load_async(&[ "examples/assets/Gledista_Triacanthos.obj", "examples/assets/Gledista_Triacanthos.mtl", "examples/assets/maps/gleditsia_triacanthos_flowers_color.jpg", "examples/assets/maps/gleditsia_triacanthos_flowers_mask.jpg", "examples/assets/maps/gleditsia_triacanthos_bark_reflect.jpg", "examples/assets/maps/gleditsia_triacanthos_bark2_a1.jpg", "examples/assets/maps/gleditsia_tri
acanthos_leaf_color_b1.jpg", "examples/assets/maps/gleditsia_triacanthos_leaf_mask.jpg", ]) .await .unwrap(); let (mut meshes, materials) = loaded.obj(".obj").unwrap(); let mut models = Vec::new(); for mut mesh in meshes.drain(..) { mesh.compute_normals(); let mut model = Model::new_with_material( &context, &mesh, PhysicalMaterial::new( &context, &materials .iter() .find(|m| Some(&m.name) == mesh.material_name.as_ref()) .unwrap(), ) .unwrap(), ) .unwrap(); model.material.render_states.cull = Cull::Back; models.push(model); } let ambient = AmbientLight::new(&context, 0.3, Color::WHITE).unwrap(); let directional = DirectionalLight::new(&context, 4.0, Color::WHITE, &vec3(-1.0, -1.0, -1.0)).unwrap(); let mut aabb = AxisAlignedBoundingBox::EMPTY; models.iter().for_each(|m| { aabb.expand_with_aabb(&m.aabb()); }); let size = aabb.size(); let t = 100; let mut positions = Vec::new(); for x in -t..t + 1 { for y in -t..t + 1 { if x != 0 || y != 0 { positions.push(vec3(size.x * x as f32, 0.0, size.y * y as f32)); } } } let imposters = Imposters::new( &context, &positions, &models.iter().map(|m| m as &dyn Object).collect::<Vec<_>>(), &[&ambient, &directional], 256, ) .unwrap(); let mut plane = Model::new_with_material( &context, &CpuMesh { positions: Positions::F32(vec![ vec3(-10000.0, 0.0, 10000.0), vec3(10000.0, 0.0, 10000.0), vec3(0.0, 0.0, -10000.0), ]), normals: Some(vec![ vec3(0.0, 1.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 1.0, 0.0), ]), ..Default::default() }, PhysicalMaterial { albedo: Color::new_opaque(128, 200, 70), metallic: 0.0, roughness: 1.0, ..Default::default() }, ) .unwrap(); plane.material.render_states.cull = Cull::Back; models.push(plane); window .render_loop(move |mut frame_input| { let mut redraw = frame_input.first_frame; redraw |= camera.set_viewport(frame_input.viewport).unwrap(); redraw |= control .handle_events(&mut camera, &mut frame_input.events) .unwrap(); if redraw { let mut models = models.iter().map(|m| m as &dyn Object).collect::<Vec<_>>(); models.push(&imposters); frame_input .screen() .clear(ClearState::color_and_depth(0.8, 0.8, 0.8, 1.0, 1.0)) .unwrap() .render(&camera, &models, &[&ambient, &directional]) .unwrap(); } FrameOutput { swap_buffers: redraw, ..Default::default() } }) .unwrap(); }
function_block-function_prefixed
[ { "content": "pub fn run() {\n\n let window = Window::new(WindowSettings {\n\n title: \"Fireworks!\".to_string(),\n\n max_size: Some((1280, 720)),\n\n ..Default::default()\n\n })\n\n .unwrap();\n\n let context = window.gl().unwrap();\n\n\n\n let mut camera = Camera::new_persp...
Rust
src/elf_sections.rs
Caduser2020/multiboot2-elf64
e6aff7cbdc2ab75a85de0b0b9c0ed9f095ff03ad
use header::Tag; #[derive(Debug)] pub struct ElfSectionsTag { inner: *const ElfSectionsTagInner, offset: usize, } pub unsafe fn elf_sections_tag(tag: &Tag, offset: usize) -> ElfSectionsTag { assert_eq!(9, tag.typ); let es = ElfSectionsTag { inner: (tag as *const Tag).offset(1) as *const ElfSectionsTagInner, offset, }; assert!((es.get().entry_size * es.get().shndx) <= tag.size); es } #[derive(Clone, Copy, Debug)] #[repr(C, packed)] struct ElfSectionsTagInner { number_of_sections: u32, entry_size: u32, shndx: u32, } impl ElfSectionsTag { pub fn sections(&self) -> ElfSectionIter { let string_section_offset = (self.get().shndx * self.get().entry_size) as isize; let string_section_ptr = unsafe { self.first_section().offset(string_section_offset) as *const _ }; ElfSectionIter { current_section: self.first_section(), remaining_sections: self.get().number_of_sections, entry_size: self.get().entry_size, string_section: string_section_ptr, offset: self.offset, } } fn first_section(&self) -> *const u8 { (unsafe { self.inner.offset(1) }) as *const _ } fn get(&self) -> &ElfSectionsTagInner { unsafe { &*self.inner } } } #[derive(Clone, Debug)] pub struct ElfSectionIter { current_section: *const u8, remaining_sections: u32, entry_size: u32, string_section: *const u8, offset: usize, } impl Iterator for ElfSectionIter { type Item = ElfSection; fn next(&mut self) -> Option<ElfSection> { while self.remaining_sections != 0 { let section = ElfSection { inner: self.current_section, string_section: self.string_section, entry_size: self.entry_size, offset: self.offset, }; self.current_section = unsafe { self.current_section.offset(self.entry_size as isize) }; self.remaining_sections -= 1; if section.section_type() != ElfSectionType::Unused { return Some(section); } } None } } #[derive(Debug)] pub struct ElfSection { inner: *const u8, string_section: *const u8, entry_size: u32, offset: usize, } #[derive(Clone, Copy, Debug)] #[repr(C, packed)] struct ElfSectionInner32 { name_index: u32, typ: u32, flags: u32, addr: u32, offset: u32, size: u32, link: u32, info: u32, addralign: u32, entry_size: u32, } #[derive(Clone, Copy, Debug)] #[repr(C, packed)] struct ElfSectionInner64 { name_index: u32, typ: u32, flags: u64, addr: u64, offset: u64, size: u64, link: u32, info: u32, addralign: u64, entry_size: u64, } impl ElfSection { pub fn section_type(&self) -> ElfSectionType { match self.get().typ() { 0 => ElfSectionType::Unused, 1 => ElfSectionType::ProgramSection, 2 => ElfSectionType::LinkerSymbolTable, 3 => ElfSectionType::StringTable, 4 => ElfSectionType::RelaRelocation, 5 => ElfSectionType::SymbolHashTable, 6 => ElfSectionType::DynamicLinkingTable, 7 => ElfSectionType::Note, 8 => ElfSectionType::Uninitialized, 9 => ElfSectionType::RelRelocation, 10 => ElfSectionType::Reserved, 11 => ElfSectionType::DynamicLoaderSymbolTable, 0x6000_0000...0x6FFF_FFFF => ElfSectionType::EnvironmentSpecific, 0x7000_0000...0x7FFF_FFFF => ElfSectionType::ProcessorSpecific, _ => panic!(), } } pub fn section_type_raw(&self) -> u32 { self.get().typ() } pub fn name(&self) -> &str { use core::{str, slice}; let name_ptr = unsafe { self.string_table().offset(self.get().name_index() as isize) }; let strlen = { let mut len = 0; while unsafe { *name_ptr.offset(len) } != 0 { len += 1; } len as usize }; str::from_utf8(unsafe { slice::from_raw_parts(name_ptr, strlen) }).unwrap() } pub fn start_address(&self) -> u64 { self.get().addr() } pub fn end_address(&self) -> u64 { self.get().addr() + self.get().size() } pub fn size(&self) -> u64 { self.get().size() } pub fn addralign(&self) -> u64 { self.get().addralign() } pub fn flags(&self) -> ElfSectionFlags { ElfSectionFlags::from_bits_truncate(self.get().flags()) } pub fn is_allocated(&self) -> bool { self.flags().contains(ElfSectionFlags::ALLOCATED) } fn get(&self) -> &ElfSectionInner { match self.entry_size { 40 => unsafe { &*(self.inner as *const ElfSectionInner32) }, 64 => unsafe { &*(self.inner as *const ElfSectionInner64) }, _ => panic!(), } } unsafe fn string_table(&self) -> *const u8 { let addr = match self.entry_size { 40 => (*(self.string_section as *const ElfSectionInner32)).addr as usize, 64 => (*(self.string_section as *const ElfSectionInner64)).addr as usize, _ => panic!(), }; (addr + self.offset) as *const _ } } trait ElfSectionInner { fn name_index(&self) -> u32; fn typ(&self) -> u32; fn flags(&self) -> u64; fn addr(&self) -> u64; fn size(&self) -> u64; fn addralign(&self) -> u64; } impl ElfSectionInner for ElfSectionInner32 { fn name_index(&self) -> u32 { self.name_index } fn typ(&self) -> u32 { self.typ } fn flags(&self) -> u64 { self.flags.into() } fn addr(&self) -> u64 { self.addr.into() } fn size(&self) -> u64 { self.size.into() } fn addralign(&self) -> u64 { self.addralign.into() } } impl ElfSectionInner for ElfSectionInner64 { fn name_index(&self) -> u32 { self.name_index } fn typ(&self) -> u32 { self.typ } fn flags(&self) -> u64 { self.flags } fn addr(&self) -> u64 { self.addr } fn size(&self) -> u64 { self.size } fn addralign(&self) -> u64 { self.addralign.into() } } #[derive(PartialEq, Eq, Debug, Copy, Clone)] #[repr(u32)] pub enum ElfSectionType { Unused = 0, ProgramSection = 1, LinkerSymbolTable = 2, StringTable = 3, RelaRelocation = 4, SymbolHashTable = 5, DynamicLinkingTable = 6, Note = 7, Uninitialized = 8, RelRelocation = 9, Reserved = 10, DynamicLoaderSymbolTable = 11, EnvironmentSpecific = 0x6000_0000, ProcessorSpecific = 0x7000_0000, } bitflags! { pub struct ElfSectionFlags: u64 { const WRITABLE = 0x1; const ALLOCATED = 0x2; const EXECUTABLE = 0x4; } }
use header::Tag; #[derive(Debug)] pub struct ElfSectionsTag { inner: *const ElfSectionsTagInner, offset: usize, } pub unsafe fn elf_sections_tag(tag: &Tag, offset: usize) -> ElfSectionsTag { assert_eq!(9, tag.typ); let es = ElfSectionsTag { inner: (tag as *const Tag).offset(1) as *const ElfSectionsTagInner, offset, }; assert!((es.get().entry_size * es.get().shndx) <= tag.size); es } #[derive(Clone, Copy, Debug)] #[repr(C, packed)] struct ElfSectionsTagInner { number_of_sections: u32, entry_size: u32, shndx: u32, } impl ElfSectionsTag { pub fn sections(&self) -> ElfSectionIter { let string_section_offset = (self.get().shndx * self.get().entry_size) as isize; let string_section_ptr = unsafe { self.first_section().offset(string_section_offset) as *const _ }; Elf
-> u64 { self.size.into() } fn addralign(&self) -> u64 { self.addralign.into() } } impl ElfSectionInner for ElfSectionInner64 { fn name_index(&self) -> u32 { self.name_index } fn typ(&self) -> u32 { self.typ } fn flags(&self) -> u64 { self.flags } fn addr(&self) -> u64 { self.addr } fn size(&self) -> u64 { self.size } fn addralign(&self) -> u64 { self.addralign.into() } } #[derive(PartialEq, Eq, Debug, Copy, Clone)] #[repr(u32)] pub enum ElfSectionType { Unused = 0, ProgramSection = 1, LinkerSymbolTable = 2, StringTable = 3, RelaRelocation = 4, SymbolHashTable = 5, DynamicLinkingTable = 6, Note = 7, Uninitialized = 8, RelRelocation = 9, Reserved = 10, DynamicLoaderSymbolTable = 11, EnvironmentSpecific = 0x6000_0000, ProcessorSpecific = 0x7000_0000, } bitflags! { pub struct ElfSectionFlags: u64 { const WRITABLE = 0x1; const ALLOCATED = 0x2; const EXECUTABLE = 0x4; } }
SectionIter { current_section: self.first_section(), remaining_sections: self.get().number_of_sections, entry_size: self.get().entry_size, string_section: string_section_ptr, offset: self.offset, } } fn first_section(&self) -> *const u8 { (unsafe { self.inner.offset(1) }) as *const _ } fn get(&self) -> &ElfSectionsTagInner { unsafe { &*self.inner } } } #[derive(Clone, Debug)] pub struct ElfSectionIter { current_section: *const u8, remaining_sections: u32, entry_size: u32, string_section: *const u8, offset: usize, } impl Iterator for ElfSectionIter { type Item = ElfSection; fn next(&mut self) -> Option<ElfSection> { while self.remaining_sections != 0 { let section = ElfSection { inner: self.current_section, string_section: self.string_section, entry_size: self.entry_size, offset: self.offset, }; self.current_section = unsafe { self.current_section.offset(self.entry_size as isize) }; self.remaining_sections -= 1; if section.section_type() != ElfSectionType::Unused { return Some(section); } } None } } #[derive(Debug)] pub struct ElfSection { inner: *const u8, string_section: *const u8, entry_size: u32, offset: usize, } #[derive(Clone, Copy, Debug)] #[repr(C, packed)] struct ElfSectionInner32 { name_index: u32, typ: u32, flags: u32, addr: u32, offset: u32, size: u32, link: u32, info: u32, addralign: u32, entry_size: u32, } #[derive(Clone, Copy, Debug)] #[repr(C, packed)] struct ElfSectionInner64 { name_index: u32, typ: u32, flags: u64, addr: u64, offset: u64, size: u64, link: u32, info: u32, addralign: u64, entry_size: u64, } impl ElfSection { pub fn section_type(&self) -> ElfSectionType { match self.get().typ() { 0 => ElfSectionType::Unused, 1 => ElfSectionType::ProgramSection, 2 => ElfSectionType::LinkerSymbolTable, 3 => ElfSectionType::StringTable, 4 => ElfSectionType::RelaRelocation, 5 => ElfSectionType::SymbolHashTable, 6 => ElfSectionType::DynamicLinkingTable, 7 => ElfSectionType::Note, 8 => ElfSectionType::Uninitialized, 9 => ElfSectionType::RelRelocation, 10 => ElfSectionType::Reserved, 11 => ElfSectionType::DynamicLoaderSymbolTable, 0x6000_0000...0x6FFF_FFFF => ElfSectionType::EnvironmentSpecific, 0x7000_0000...0x7FFF_FFFF => ElfSectionType::ProcessorSpecific, _ => panic!(), } } pub fn section_type_raw(&self) -> u32 { self.get().typ() } pub fn name(&self) -> &str { use core::{str, slice}; let name_ptr = unsafe { self.string_table().offset(self.get().name_index() as isize) }; let strlen = { let mut len = 0; while unsafe { *name_ptr.offset(len) } != 0 { len += 1; } len as usize }; str::from_utf8(unsafe { slice::from_raw_parts(name_ptr, strlen) }).unwrap() } pub fn start_address(&self) -> u64 { self.get().addr() } pub fn end_address(&self) -> u64 { self.get().addr() + self.get().size() } pub fn size(&self) -> u64 { self.get().size() } pub fn addralign(&self) -> u64 { self.get().addralign() } pub fn flags(&self) -> ElfSectionFlags { ElfSectionFlags::from_bits_truncate(self.get().flags()) } pub fn is_allocated(&self) -> bool { self.flags().contains(ElfSectionFlags::ALLOCATED) } fn get(&self) -> &ElfSectionInner { match self.entry_size { 40 => unsafe { &*(self.inner as *const ElfSectionInner32) }, 64 => unsafe { &*(self.inner as *const ElfSectionInner64) }, _ => panic!(), } } unsafe fn string_table(&self) -> *const u8 { let addr = match self.entry_size { 40 => (*(self.string_section as *const ElfSectionInner32)).addr as usize, 64 => (*(self.string_section as *const ElfSectionInner64)).addr as usize, _ => panic!(), }; (addr + self.offset) as *const _ } } trait ElfSectionInner { fn name_index(&self) -> u32; fn typ(&self) -> u32; fn flags(&self) -> u64; fn addr(&self) -> u64; fn size(&self) -> u64; fn addralign(&self) -> u64; } impl ElfSectionInner for ElfSectionInner32 { fn name_index(&self) -> u32 { self.name_index } fn typ(&self) -> u32 { self.typ } fn flags(&self) -> u64 { self.flags.into() } fn addr(&self) -> u64 { self.addr.into() } fn size(&self)
random
[]
Rust
opal/macros/src/parser.rs
Txuritan/varela
4d3446b41c7aa7308cf8402c4ff0ddaebde3a08d
pub fn parse(text: &str) -> Vec<Stage4> { pass_4(pass_3(pass_2(pass_1(text)))) } enum Stage1 { Open, Close, Other(char), } #[inline] fn pass_1(text: &str) -> Vec<Stage1> { let mut iter = text.chars().peekable(); let mut tokens = Vec::new(); while let Some(c) = iter.next() { match c { '{' if iter.peek().map(|c| *c == '{').unwrap_or(false) => { let _c = iter.next(); tokens.push(Stage1::Open); } '}' if iter.peek().map(|c| *c == '}').unwrap_or(false) => { let _c = iter.next(); tokens.push(Stage1::Close); } c => tokens.push(Stage1::Other(c)), } } tokens } enum Stage2 { Open, Close, Other(String), } #[inline] fn pass_2(stage_1: Vec<Stage1>) -> Vec<Stage2> { let mut tokens = Vec::new(); for token in stage_1 { match token { Stage1::Open => tokens.push(Stage2::Open), Stage1::Close => tokens.push(Stage2::Close), Stage1::Other(c) if tokens .last() .map(|token| matches!(token, Stage2::Other(_))) .unwrap_or(false) => { if let Some(Stage2::Other(other)) = tokens.last_mut() { other.push(c); } } Stage1::Other(c) => tokens.push(Stage2::Other(String::from(c))), } } tokens } enum Stage3 { Expr(String), Other(String), } #[inline] fn pass_3(stage_2: Vec<Stage2>) -> Vec<Stage3> { let mut tokens = Vec::new(); let mut take = false; for token in stage_2 { match token { Stage2::Open => take = true, Stage2::Close => take = false, Stage2::Other(other) => { if take { tokens.push(Stage3::Expr(other)); } else { tokens.push(Stage3::Other(other)); } } } } tokens } #[derive(Debug)] pub enum Stage4 { Expr(String), ExprAssign(String), ExprRender(String), If(String, Vec<Stage4>, Option<Vec<Stage4>>), For(String, Vec<Stage4>), Other(String), } #[inline] fn pass_4(stage_3: Vec<Stage3>) -> Vec<Stage4> { let mut iter = stage_3.into_iter(); let mut tokens = Vec::new(); while let Some(token) = iter.next() { match token { Stage3::Expr(expr) => { let trimmed_expr = expr.trim(); if trimmed_expr.starts_with('#') { let trimmed_expr = trimmed_expr.trim_start_matches('#'); if trimmed_expr.starts_with("if") { let (if_exprs, else_exprs) = pass_4_if(&mut iter); tokens.push(Stage4::If(trimmed_expr.to_string(), if_exprs, else_exprs)); } else if trimmed_expr.starts_with("for") { tokens.push(Stage4::For(trimmed_expr.to_string(), pass_4_for(&mut iter))); } } else if trimmed_expr.starts_with("let") && trimmed_expr.ends_with(';') { tokens.push(Stage4::ExprAssign(expr)); } else if trimmed_expr.ends_with(".render(writer)") { tokens.push(Stage4::ExprRender(expr)); } else { tokens.push(Stage4::Expr(expr)); } } Stage3::Other(other) => tokens.push(Stage4::Other(other)), } } tokens } #[allow(clippy::while_let_on_iterator)] #[inline] fn pass_4_if<I>(iter: &mut I) -> (Vec<Stage4>, Option<Vec<Stage4>>) where I: Iterator<Item = Stage3>, { let mut if_exprs = Vec::new(); let mut else_exprs = Vec::new(); let mut in_else = false; while let Some(token) = iter.next() { let mut_expr = if in_else { &mut else_exprs } else { &mut if_exprs }; match token { Stage3::Expr(expr) => { let trimmed_expr = expr.trim(); if trimmed_expr.starts_with('#') { let trimmed_expr = trimmed_expr.trim_start_matches('#'); if trimmed_expr.starts_with("if") { mut_expr.push({ let (if_exprs, else_exprs) = pass_4_if(iter); Stage4::If(trimmed_expr.to_string(), if_exprs, else_exprs) }); } else if trimmed_expr.starts_with("for") { mut_expr.push(Stage4::For(trimmed_expr.to_string(), pass_4_for(iter))); } } else if trimmed_expr == "else" { in_else = true; } else if trimmed_expr.starts_with('/') { break; } else if trimmed_expr.starts_with("let") && trimmed_expr.ends_with(';') { mut_expr.push(Stage4::ExprAssign(expr)); } else if trimmed_expr.ends_with(".render(writer)") { mut_expr.push(Stage4::ExprRender(expr)); } else { mut_expr.push(Stage4::Expr(expr)); } } Stage3::Other(other) => mut_expr.push(Stage4::Other(other)), } } ( if_exprs, if else_exprs.is_empty() { None } else { Some(else_exprs) }, ) } #[allow(clippy::while_let_on_iterator)] #[inline] fn pass_4_for<I>(iter: &mut I) -> Vec<Stage4> where I: Iterator<Item = Stage3>, { let mut exprs = Vec::new(); while let Some(token) = iter.next() { match token { Stage3::Expr(expr) => { let trimmed_expr = expr.trim(); if trimmed_expr.starts_with('#') { let trimmed_expr = trimmed_expr.trim_start_matches('#'); if trimmed_expr.starts_with("if") { let (if_exprs, else_exprs) = pass_4_if(iter); exprs.push(Stage4::If(trimmed_expr.to_string(), if_exprs, else_exprs)); } else if trimmed_expr.starts_with("for") { exprs.push(Stage4::For(trimmed_expr.to_string(), pass_4_for(iter))); } } else if trimmed_expr.starts_with('/') { break; } else if trimmed_expr.starts_with("let") && trimmed_expr.ends_with(';') { exprs.push(Stage4::ExprAssign(expr)); } else if trimmed_expr.ends_with(".render(writer)") { exprs.push(Stage4::ExprRender(expr)); } else { exprs.push(Stage4::Expr(expr)); } } Stage3::Other(other) => exprs.push(Stage4::Other(other)), } } exprs }
pub fn parse(text: &str) -> Vec<Stage4> { pass_4(pass_3(pass_2(pass_1(text)))) } enum Stage1 { Open, Close, Other(char), } #[inline] fn pass_1(text: &str) -> Vec<Stage1> { let mut iter = text.chars().peekable(); let mut tokens = Vec::new(); while let Some(c) = iter.next() { match c { '{' if iter.peek().map(|c| *c == '{').unwrap_or(false) => { let _c = iter.next(); tokens.push(Stage1::Open); } '}' if iter.peek().map(|c| *c == '}').unwrap_or(false) => { let _c = iter.next(); tokens.push(Stage1::Close); } c => tokens.push(Stage1::Other(c)), } } tokens } enum Stage2 { Open, Close, Other(String), } #[inline] fn pass_2(stage_1: Vec<Stage1>) -> Vec<Stage2> { let mut tokens = Vec::new(); for token in stage_1 { match token { Stage1::Open => tokens.push(Stage2::Open), Stage1::Close => tokens.push(Stage2::Close), Stage1::Other(c) if tokens .last() .map(|token| matches!(token, Stage2::Other(_))) .unwrap_or(false) => { if let Some(Stage2::Other(other)) = tokens.last_mut() { other.push(c); } } Stage1::Other(c) => tokens.push(Stage2::Other(String::from(c))), } } tokens } enum Stage3 { Expr(String), Other(String), } #[inline] fn pass_3(stage_2: Vec<Stage2>) -> Vec<Stage3> { let mut tokens = Vec::new(); let mut take = false; for token in stage_2 { match token { Stage2::Open => take = true, Stage2::Close => take = false, Stage2::Other(other) => { if take { tokens.push(Stage3::Expr(other)); } else { tokens.push(Stage3::Other(other)); } } } } tokens } #[derive(Debug)] pub enum Stage4 { Expr(String), ExprAssign(String), ExprRender(String), If(String, Vec<Stage4>, Option<Vec<Stage4>>), For(String, Vec<Stage4>), Other(String), } #[inline] fn pass_4(stage_3: Vec<Stage3>) -> Vec<Stage4> { let mut iter = stage_3.into_iter(); let mut tokens = Vec::new(); while let Some(token) = iter.next() { match token { Stage3::Expr(expr) => { let trimmed_expr = expr.trim(); if trimmed_expr.starts_with('#') { let trimmed_expr = trimmed_expr.trim_start_matches('#'); if trimmed_expr.starts_with("if") { let (if_exprs, else_exprs) = pass_4_if(&mut iter); tokens.push(Stage4::If(trimmed_expr.to_string(), if_exprs, else_exprs)); } else if trimmed_expr.starts_with("for") { tokens.push(Stage4::For(trimmed_expr.to_string(), pass_4_for(&mut iter))); } } else if trimmed_expr.starts_with("let") && trimmed_expr.ends_with(';') { tokens.push(Stage4::ExprAssign(expr)); } else if trimmed_expr.ends_with(".render(writer)") { tokens.push(Stage4::ExprRender(expr)); } else { tokens.push(Stage4::Expr(expr)); } } Stage3::Other(other) => tokens.push(Stage4::Other(other)), } } tokens } #[allow(clippy::while_let_on_iterator)] #[inline]
#[allow(clippy::while_let_on_iterator)] #[inline] fn pass_4_for<I>(iter: &mut I) -> Vec<Stage4> where I: Iterator<Item = Stage3>, { let mut exprs = Vec::new(); while let Some(token) = iter.next() { match token { Stage3::Expr(expr) => { let trimmed_expr = expr.trim(); if trimmed_expr.starts_with('#') { let trimmed_expr = trimmed_expr.trim_start_matches('#'); if trimmed_expr.starts_with("if") { let (if_exprs, else_exprs) = pass_4_if(iter); exprs.push(Stage4::If(trimmed_expr.to_string(), if_exprs, else_exprs)); } else if trimmed_expr.starts_with("for") { exprs.push(Stage4::For(trimmed_expr.to_string(), pass_4_for(iter))); } } else if trimmed_expr.starts_with('/') { break; } else if trimmed_expr.starts_with("let") && trimmed_expr.ends_with(';') { exprs.push(Stage4::ExprAssign(expr)); } else if trimmed_expr.ends_with(".render(writer)") { exprs.push(Stage4::ExprRender(expr)); } else { exprs.push(Stage4::Expr(expr)); } } Stage3::Other(other) => exprs.push(Stage4::Other(other)), } } exprs }
fn pass_4_if<I>(iter: &mut I) -> (Vec<Stage4>, Option<Vec<Stage4>>) where I: Iterator<Item = Stage3>, { let mut if_exprs = Vec::new(); let mut else_exprs = Vec::new(); let mut in_else = false; while let Some(token) = iter.next() { let mut_expr = if in_else { &mut else_exprs } else { &mut if_exprs }; match token { Stage3::Expr(expr) => { let trimmed_expr = expr.trim(); if trimmed_expr.starts_with('#') { let trimmed_expr = trimmed_expr.trim_start_matches('#'); if trimmed_expr.starts_with("if") { mut_expr.push({ let (if_exprs, else_exprs) = pass_4_if(iter); Stage4::If(trimmed_expr.to_string(), if_exprs, else_exprs) }); } else if trimmed_expr.starts_with("for") { mut_expr.push(Stage4::For(trimmed_expr.to_string(), pass_4_for(iter))); } } else if trimmed_expr == "else" { in_else = true; } else if trimmed_expr.starts_with('/') { break; } else if trimmed_expr.starts_with("let") && trimmed_expr.ends_with(';') { mut_expr.push(Stage4::ExprAssign(expr)); } else if trimmed_expr.ends_with(".render(writer)") { mut_expr.push(Stage4::ExprRender(expr)); } else { mut_expr.push(Stage4::Expr(expr)); } } Stage3::Other(other) => mut_expr.push(Stage4::Other(other)), } } ( if_exprs, if else_exprs.is_empty() { None } else { Some(else_exprs) }, ) }
function_block-full_function
[ { "content": "pub fn write_string<W: Write>(writer: &mut W, text: &str) -> Result<(), Error> {\n\n let bytes = text.as_bytes();\n\n\n\n write_length(writer, bytes.len())?;\n\n writer.write_all(bytes)?;\n\n\n\n Ok(())\n\n}\n\n\n\npub mod structure {\n\n use {\n\n crate::{bytes::*, io, Error...
Rust
guifuzz/src/lib.rs
gamozolabs/guifuzz
471d744e0e46d21cad39e4287ddc6f13c9811b17
pub mod winbindings; pub mod rng; use std::error::Error; use std::collections::{HashSet, HashMap}; use std::sync::{Mutex, Arc}; pub use rng::Rng; pub use winbindings::Window; pub type FuzzInput = Arc<Vec<FuzzerAction>>; #[derive(Default)] pub struct Statistics { pub fuzz_cases: u64, pub coverage_db: HashMap<(Arc<String>, usize), FuzzInput>, pub input_db: HashSet<FuzzInput>, pub input_list: Vec<FuzzInput>, pub unique_action_set: HashSet<FuzzerAction>, pub unique_actions: Vec<FuzzerAction>, pub crashes: u64, pub crash_db: HashMap<String, FuzzInput>, } #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum FuzzerAction { LeftClick { idx: usize }, Close, MenuAction { menu_id: u32 }, KeyPress { key: usize }, } pub fn perform_actions(pid: u32, actions: &[FuzzerAction]) -> Result<(), Box<dyn Error>>{ let primary_window = Window::attach_pid(pid, "Calculator")?; for &action in actions { match action { FuzzerAction::LeftClick { idx } => { let sub_windows = primary_window.enumerate_subwindows(); if sub_windows.is_err() { return Ok(()); } let sub_windows = sub_windows.unwrap(); if let Some(window) = sub_windows.get(idx) { let _ = window.left_click(None); } } FuzzerAction::Close => { let _ = primary_window.close(); } FuzzerAction::MenuAction { menu_id } => { let _ = primary_window.use_menu_id(menu_id); std::thread::sleep(std::time::Duration::from_millis(250)); } FuzzerAction::KeyPress { key } => { let _ = primary_window.press_key(key); } } } Ok(()) } pub fn mutate(stats: Arc<Mutex<Statistics>>) -> Result<Vec<FuzzerAction>, Box<dyn Error>> { let rng = Rng::new(); let stats = stats.lock().unwrap(); let input_sel = rng.rand() % stats.input_list.len(); let mut input: Vec<FuzzerAction> = (*stats.input_list[input_sel]).clone(); for _ in 0..((rng.rand() & 0x1f) + 1) { let sel = rng.rand() % 5; match sel { 0 => { if input.len() == 0 { continue; } let inp_start = rng.rand() % input.len(); let inp_length = rng.rand() % (rng.rand() % 64 + 1); let inp_end = std::cmp::min(inp_start + inp_length, input.len()); let donor_idx = rng.rand() % stats.input_list.len(); let donor_input = &stats.input_list[donor_idx]; if donor_input.len() == 0 { continue; } let donor_start = rng.rand() % donor_input.len(); let donor_length = rng.rand() % (rng.rand() % 64 + 1); let donor_end = std::cmp::min(donor_start + donor_length, donor_input.len()); input.splice(inp_start..inp_end, donor_input[donor_start..donor_end] .iter().cloned()); } 1 => { if input.len() == 0 { continue; } let inp_start = rng.rand() % input.len(); let inp_length = rng.rand() % (rng.rand() % 64 + 1); let inp_end = std::cmp::min(inp_start + inp_length, input.len()); input.splice(inp_start..inp_end, [].iter().cloned()); } 2 => { if input.len() == 0 { continue; } let sel = rng.rand() % input.len(); for _ in 0..rng.rand() % (rng.rand() % 64 + 1) { input.insert(sel, input[sel]); } } 3 => { if input.len() == 0 { continue; } let inp_index = rng.rand() % input.len(); let donor_idx = rng.rand() % stats.input_list.len(); let donor_input = &stats.input_list[donor_idx]; if donor_input.len() == 0 { continue; } let donor_start = rng.rand() % donor_input.len(); let donor_length = rng.rand() % (rng.rand() % 64 + 1); let donor_end = std::cmp::min(donor_start + donor_length, donor_input.len()); let new_inp: Vec<FuzzerAction> = input[0..inp_index].iter() .chain(donor_input[donor_start..donor_end].iter()) .chain(input[inp_index..].iter()).cloned().collect(); input = new_inp; } 4 => { if stats.unique_actions.len() == 0 || input.len() == 0 { continue; } let rand_action = stats.unique_actions[ rng.rand() % stats.unique_actions.len()]; input.insert(rng.rand() % input.len(), rand_action); } _ => panic!("Unreachable"), } } Ok(input) } pub fn generator(pid: u32) -> Result<Vec<FuzzerAction>, Box<dyn Error>> { let mut actions = Vec::new(); let rng = Rng::new(); let primary_window = Window::attach_pid(pid, "Calculator")?; loop { { let sub_windows = primary_window.enumerate_subwindows(); if sub_windows.is_err() { return Ok(actions); } let sub_windows = sub_windows.unwrap(); let sel = rng.rand() % sub_windows.len(); let window = sub_windows[sel]; actions.push(FuzzerAction::LeftClick { idx: sel }); let _ = window.left_click(None); } { let key = ((rng.rand() % 10) as u8 + b'0') as usize; actions.push(FuzzerAction::KeyPress { key }); let _ = primary_window.press_key(key); } if rng.rand() & 0x1f == 0 { let key = rng.rand() as u8 as usize; actions.push(FuzzerAction::KeyPress { key }); let _ = primary_window.press_key(key); } if (rng.rand() & 0xff) == 0 { actions.push(FuzzerAction::Close); let _ = primary_window.close(); } if (rng.rand() & 0x1f) == 0 { if let Ok(menus) = primary_window.enum_menus() { let menus: Vec<u32> = menus.iter().cloned().collect(); let sel = menus[rng.rand() % menus.len()]; actions.push(FuzzerAction::MenuAction { menu_id: sel }); let _ = primary_window.use_menu_id(sel); std::thread::sleep(std::time::Duration::from_millis(250)); } } } }
pub mod winbindings; pub mod rng; use std::error::Error; use std::collections::{HashSet, HashMap}; use std::sync::{Mutex, Arc}; pub use rng::Rng; pub use winbindings::Window; pub type FuzzInput = Arc<Vec<FuzzerAction>>; #[derive(Default)] pub struct Statistics { pub fuzz_cases: u64, pub coverage_db: HashMap<(Arc<String>, usize), FuzzInput>, pub input_db: HashSet<FuzzInput>, pub input_list: Vec<FuzzInput>, pub unique_action_set: HashSet<FuzzerAction>, pub unique_actions: Vec<FuzzerAction>, pub crashes: u64, pub crash_db: HashMap<String, FuzzInput>, } #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum FuzzerAction { LeftClick { idx: usize }, Close, MenuAction { menu_id: u32 }, KeyPress { key: usize }, } pub fn perform_actions(pid: u32, actions: &[FuzzerAction]) -> Result<(), Box<dyn Error>>{
pub fn mutate(stats: Arc<Mutex<Statistics>>) -> Result<Vec<FuzzerAction>, Box<dyn Error>> { let rng = Rng::new(); let stats = stats.lock().unwrap(); let input_sel = rng.rand() % stats.input_list.len(); let mut input: Vec<FuzzerAction> = (*stats.input_list[input_sel]).clone(); for _ in 0..((rng.rand() & 0x1f) + 1) { let sel = rng.rand() % 5; match sel { 0 => { if input.len() == 0 { continue; } let inp_start = rng.rand() % input.len(); let inp_length = rng.rand() % (rng.rand() % 64 + 1); let inp_end = std::cmp::min(inp_start + inp_length, input.len()); let donor_idx = rng.rand() % stats.input_list.len(); let donor_input = &stats.input_list[donor_idx]; if donor_input.len() == 0 { continue; } let donor_start = rng.rand() % donor_input.len(); let donor_length = rng.rand() % (rng.rand() % 64 + 1); let donor_end = std::cmp::min(donor_start + donor_length, donor_input.len()); input.splice(inp_start..inp_end, donor_input[donor_start..donor_end] .iter().cloned()); } 1 => { if input.len() == 0 { continue; } let inp_start = rng.rand() % input.len(); let inp_length = rng.rand() % (rng.rand() % 64 + 1); let inp_end = std::cmp::min(inp_start + inp_length, input.len()); input.splice(inp_start..inp_end, [].iter().cloned()); } 2 => { if input.len() == 0 { continue; } let sel = rng.rand() % input.len(); for _ in 0..rng.rand() % (rng.rand() % 64 + 1) { input.insert(sel, input[sel]); } } 3 => { if input.len() == 0 { continue; } let inp_index = rng.rand() % input.len(); let donor_idx = rng.rand() % stats.input_list.len(); let donor_input = &stats.input_list[donor_idx]; if donor_input.len() == 0 { continue; } let donor_start = rng.rand() % donor_input.len(); let donor_length = rng.rand() % (rng.rand() % 64 + 1); let donor_end = std::cmp::min(donor_start + donor_length, donor_input.len()); let new_inp: Vec<FuzzerAction> = input[0..inp_index].iter() .chain(donor_input[donor_start..donor_end].iter()) .chain(input[inp_index..].iter()).cloned().collect(); input = new_inp; } 4 => { if stats.unique_actions.len() == 0 || input.len() == 0 { continue; } let rand_action = stats.unique_actions[ rng.rand() % stats.unique_actions.len()]; input.insert(rng.rand() % input.len(), rand_action); } _ => panic!("Unreachable"), } } Ok(input) } pub fn generator(pid: u32) -> Result<Vec<FuzzerAction>, Box<dyn Error>> { let mut actions = Vec::new(); let rng = Rng::new(); let primary_window = Window::attach_pid(pid, "Calculator")?; loop { { let sub_windows = primary_window.enumerate_subwindows(); if sub_windows.is_err() { return Ok(actions); } let sub_windows = sub_windows.unwrap(); let sel = rng.rand() % sub_windows.len(); let window = sub_windows[sel]; actions.push(FuzzerAction::LeftClick { idx: sel }); let _ = window.left_click(None); } { let key = ((rng.rand() % 10) as u8 + b'0') as usize; actions.push(FuzzerAction::KeyPress { key }); let _ = primary_window.press_key(key); } if rng.rand() & 0x1f == 0 { let key = rng.rand() as u8 as usize; actions.push(FuzzerAction::KeyPress { key }); let _ = primary_window.press_key(key); } if (rng.rand() & 0xff) == 0 { actions.push(FuzzerAction::Close); let _ = primary_window.close(); } if (rng.rand() & 0x1f) == 0 { if let Ok(menus) = primary_window.enum_menus() { let menus: Vec<u32> = menus.iter().cloned().collect(); let sel = menus[rng.rand() % menus.len()]; actions.push(FuzzerAction::MenuAction { menu_id: sel }); let _ = primary_window.use_menu_id(sel); std::thread::sleep(std::time::Duration::from_millis(250)); } } } }
let primary_window = Window::attach_pid(pid, "Calculator")?; for &action in actions { match action { FuzzerAction::LeftClick { idx } => { let sub_windows = primary_window.enumerate_subwindows(); if sub_windows.is_err() { return Ok(()); } let sub_windows = sub_windows.unwrap(); if let Some(window) = sub_windows.get(idx) { let _ = window.left_click(None); } } FuzzerAction::Close => { let _ = primary_window.close(); } FuzzerAction::MenuAction { menu_id } => { let _ = primary_window.use_menu_id(menu_id); std::thread::sleep(std::time::Duration::from_millis(250)); } FuzzerAction::KeyPress { key } => { let _ = primary_window.press_key(key); } } } Ok(()) }
function_block-function_prefix_line
[ { "content": "/// Function invoked on breakpoints\n\n/// (debugger, tid, address of breakpoint,\n\n/// number of times breakpoint has been hit)\n\n/// If this returns false the debuggee is terminated\n\ntype BreakpointCallback = fn(&mut Debugger, u32, usize, u64) -> bool;\n\n\n\n/// Ctrl+C handler so we can re...
Rust
src/es32/ffi.rs
Michael-Lfx/opengles-rs
95aa94e600cea152047fe8642bb74a398012dab0
use types::*; pub type GLDEBUGPROC = ::std::option::Option< unsafe extern "C" fn( source: GLenum, type_: GLenum, id: GLuint, severity: GLenum, length: GLsizei, message: *const GLchar, userParam: *const GLvoid, ), >; extern "C" { pub fn glBlendBarrier(); pub fn glCopyImageSubData( srcName: GLuint, srcTarget: GLenum, srcLevel: GLint, srcX: GLint, srcY: GLint, srcZ: GLint, dstName: GLuint, dstTarget: GLenum, dstLevel: GLint, dstX: GLint, dstY: GLint, dstZ: GLint, srcWidth: GLsizei, srcHeight: GLsizei, srcDepth: GLsizei, ); pub fn glDebugMessageControl( source: GLenum, type_: GLenum, severity: GLenum, count: GLsizei, ids: *const GLuint, enabled: GLboolean, ); pub fn glDebugMessageInsert( source: GLenum, type_: GLenum, id: GLuint, severity: GLenum, length: GLsizei, buf: *const GLchar, ); pub fn glDebugMessageCallback(callback: GLDEBUGPROC, userParam: *const GLvoid); pub fn glGetDebugMessageLog( count: GLuint, bufSize: GLsizei, sources: *mut GLenum, types: *mut GLenum, ids: *mut GLuint, severities: *mut GLenum, lengths: *mut GLsizei, messageLog: *mut GLchar, ) -> GLuint; pub fn glPushDebugGroup(source: GLenum, id: GLuint, length: GLsizei, message: *const GLchar); pub fn glPopDebugGroup(); pub fn glObjectLabel(identifier: GLenum, name: GLuint, length: GLsizei, label: *const GLchar); pub fn glGetObjectLabel( identifier: GLenum, name: GLuint, bufSize: GLsizei, length: *mut GLsizei, label: *mut GLchar, ); pub fn glObjectPtrLabel(ptr: *const GLvoid, length: GLsizei, label: *const GLchar); pub fn glGetObjectPtrLabel( ptr: *const GLvoid, bufSize: GLsizei, length: *mut GLsizei, label: *mut GLchar, ); pub fn glGetPointerv(pname: GLenum, params: *mut *mut GLvoid); pub fn glEnablei(target: GLenum, index: GLuint); pub fn glDisablei(target: GLenum, index: GLuint); pub fn glBlendEquationi(buf: GLuint, mode: GLenum); pub fn glBlendEquationSeparatei(buf: GLuint, modeRGB: GLenum, modeAlpha: GLenum); pub fn glBlendFunci(buf: GLuint, src: GLenum, dst: GLenum); pub fn glBlendFuncSeparatei( buf: GLuint, srcRGB: GLenum, dstRGB: GLenum, srcAlpha: GLenum, dstAlpha: GLenum, ); pub fn glColorMaski(index: GLuint, r: GLboolean, g: GLboolean, b: GLboolean, a: GLboolean); pub fn glIsEnabledi(target: GLenum, index: GLuint) -> GLboolean; pub fn glDrawElementsBaseVertex( mode: GLenum, count: GLsizei, type_: GLenum, indices: *const GLvoid, basevertex: GLint, ); pub fn glDrawRangeElementsBaseVertex( mode: GLenum, start: GLuint, end: GLuint, count: GLsizei, type_: GLenum, indices: *const GLvoid, basevertex: GLint, ); pub fn glDrawElementsInstancedBaseVertex( mode: GLenum, count: GLsizei, type_: GLenum, indices: *const GLvoid, instancecount: GLsizei, basevertex: GLint, ); pub fn glFramebufferTexture(target: GLenum, attachment: GLenum, texture: GLuint, level: GLint); pub fn glPrimitiveBoundingBox( minX: GLfloat, minY: GLfloat, minZ: GLfloat, minW: GLfloat, maxX: GLfloat, maxY: GLfloat, maxZ: GLfloat, maxW: GLfloat, ); pub fn glGetGraphicsResetStatus() -> GLenum; pub fn glReadnPixels( x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type_: GLenum, bufSize: GLsizei, data: *mut GLvoid, ); pub fn glGetnUniformfv( program: GLuint, location: GLint, bufSize: GLsizei, params: *mut GLfloat, ); pub fn glGetnUniformiv(program: GLuint, location: GLint, bufSize: GLsizei, params: *mut GLint); pub fn glGetnUniformuiv( program: GLuint, location: GLint, bufSize: GLsizei, params: *mut GLuint, ); pub fn glMinSampleShading(value: GLfloat); pub fn glPatchParameteri(pname: GLenum, value: GLint); pub fn glTexParameterIiv(target: GLenum, pname: GLenum, params: *const GLint); pub fn glTexParameterIuiv(target: GLenum, pname: GLenum, params: *const GLuint); pub fn glGetTexParameterIiv(target: GLenum, pname: GLenum, params: *mut GLint); pub fn glGetTexParameterIuiv(target: GLenum, pname: GLenum, params: *mut GLuint); pub fn glSamplerParameterIiv(sampler: GLuint, pname: GLenum, param: *const GLint); pub fn glSamplerParameterIuiv(sampler: GLuint, pname: GLenum, param: *const GLuint); pub fn glGetSamplerParameterIiv(sampler: GLuint, pname: GLenum, params: *mut GLint); pub fn glGetSamplerParameterIuiv(sampler: GLuint, pname: GLenum, params: *mut GLuint); pub fn glTexBuffer(target: GLenum, internalformat: GLenum, buffer: GLuint); pub fn glTexBufferRange( target: GLenum, internalformat: GLenum, buffer: GLuint, offset: GLintptr, size: GLsizeiptr, ); pub fn glTexStorage3DMultisample( target: GLenum, samples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, fixedsamplelocations: GLboolean, ); }
use types::*; pub type GLDEBUGPROC = ::std::option::Option< unsafe extern "C" fn( source: GLenum, type_: GLenum, id: GLuint, severity: GLenum, length: GLsizei, message: *const GLchar, userParam: *const GLvoid, ), >; extern "C" { pub fn glBlendBarrier(); pub fn glCopyImageSubData( srcName: GLuint, srcTarget: GLenum, srcLevel: GLint, srcX: GLint, srcY: GLint, srcZ: GLint, dstName: GLuint, dstTarget: GLenum, dstLevel: GLint, dstX: GLint, dstY: GLint, dstZ: GLint, srcWidth: GLsizei, srcHeight: GLsizei, srcDepth: GLsizei, ); pub fn glDebugMessageControl( source: GLenum, type_: GLenum, severity: GLenum, count: GLsizei, ids: *const GLuint, enabled: GLboolean, ); pub fn glDebugMessageInsert( source: GLenum, type_: GLenum, id: GLuint, severity: GLenu
); pub fn glMinSampleShading(value: GLfloat); pub fn glPatchParameteri(pname: GLenum, value: GLint); pub fn glTexParameterIiv(target: GLenum, pname: GLenum, params: *const GLint); pub fn glTexParameterIuiv(target: GLenum, pname: GLenum, params: *const GLuint); pub fn glGetTexParameterIiv(target: GLenum, pname: GLenum, params: *mut GLint); pub fn glGetTexParameterIuiv(target: GLenum, pname: GLenum, params: *mut GLuint); pub fn glSamplerParameterIiv(sampler: GLuint, pname: GLenum, param: *const GLint); pub fn glSamplerParameterIuiv(sampler: GLuint, pname: GLenum, param: *const GLuint); pub fn glGetSamplerParameterIiv(sampler: GLuint, pname: GLenum, params: *mut GLint); pub fn glGetSamplerParameterIuiv(sampler: GLuint, pname: GLenum, params: *mut GLuint); pub fn glTexBuffer(target: GLenum, internalformat: GLenum, buffer: GLuint); pub fn glTexBufferRange( target: GLenum, internalformat: GLenum, buffer: GLuint, offset: GLintptr, size: GLsizeiptr, ); pub fn glTexStorage3DMultisample( target: GLenum, samples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, fixedsamplelocations: GLboolean, ); }
m, length: GLsizei, buf: *const GLchar, ); pub fn glDebugMessageCallback(callback: GLDEBUGPROC, userParam: *const GLvoid); pub fn glGetDebugMessageLog( count: GLuint, bufSize: GLsizei, sources: *mut GLenum, types: *mut GLenum, ids: *mut GLuint, severities: *mut GLenum, lengths: *mut GLsizei, messageLog: *mut GLchar, ) -> GLuint; pub fn glPushDebugGroup(source: GLenum, id: GLuint, length: GLsizei, message: *const GLchar); pub fn glPopDebugGroup(); pub fn glObjectLabel(identifier: GLenum, name: GLuint, length: GLsizei, label: *const GLchar); pub fn glGetObjectLabel( identifier: GLenum, name: GLuint, bufSize: GLsizei, length: *mut GLsizei, label: *mut GLchar, ); pub fn glObjectPtrLabel(ptr: *const GLvoid, length: GLsizei, label: *const GLchar); pub fn glGetObjectPtrLabel( ptr: *const GLvoid, bufSize: GLsizei, length: *mut GLsizei, label: *mut GLchar, ); pub fn glGetPointerv(pname: GLenum, params: *mut *mut GLvoid); pub fn glEnablei(target: GLenum, index: GLuint); pub fn glDisablei(target: GLenum, index: GLuint); pub fn glBlendEquationi(buf: GLuint, mode: GLenum); pub fn glBlendEquationSeparatei(buf: GLuint, modeRGB: GLenum, modeAlpha: GLenum); pub fn glBlendFunci(buf: GLuint, src: GLenum, dst: GLenum); pub fn glBlendFuncSeparatei( buf: GLuint, srcRGB: GLenum, dstRGB: GLenum, srcAlpha: GLenum, dstAlpha: GLenum, ); pub fn glColorMaski(index: GLuint, r: GLboolean, g: GLboolean, b: GLboolean, a: GLboolean); pub fn glIsEnabledi(target: GLenum, index: GLuint) -> GLboolean; pub fn glDrawElementsBaseVertex( mode: GLenum, count: GLsizei, type_: GLenum, indices: *const GLvoid, basevertex: GLint, ); pub fn glDrawRangeElementsBaseVertex( mode: GLenum, start: GLuint, end: GLuint, count: GLsizei, type_: GLenum, indices: *const GLvoid, basevertex: GLint, ); pub fn glDrawElementsInstancedBaseVertex( mode: GLenum, count: GLsizei, type_: GLenum, indices: *const GLvoid, instancecount: GLsizei, basevertex: GLint, ); pub fn glFramebufferTexture(target: GLenum, attachment: GLenum, texture: GLuint, level: GLint); pub fn glPrimitiveBoundingBox( minX: GLfloat, minY: GLfloat, minZ: GLfloat, minW: GLfloat, maxX: GLfloat, maxY: GLfloat, maxZ: GLfloat, maxW: GLfloat, ); pub fn glGetGraphicsResetStatus() -> GLenum; pub fn glReadnPixels( x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type_: GLenum, bufSize: GLsizei, data: *mut GLvoid, ); pub fn glGetnUniformfv( program: GLuint, location: GLint, bufSize: GLsizei, params: *mut GLfloat, ); pub fn glGetnUniformiv(program: GLuint, location: GLint, bufSize: GLsizei, params: *mut GLint); pub fn glGetnUniformuiv( program: GLuint, location: GLint, bufSize: GLsizei, params: *mut GLuint,
random
[ { "content": "pub fn get_proc_address(proc_name: &str) -> *const c_void {\n\n unsafe {\n\n let string = CString::new(proc_name).unwrap();\n\n\n\n ffi::eglGetProcAddress(string.as_ptr())\n\n }\n\n}\n\n\n\n// -------------------------------------------------------------------------------------...
Rust
src/removable_value.rs
ThomAub/vega_lite_3.rs
f962b11a818b4fe91d0ae4ec22bcf4ec02d126ef
use serde::de::{Error, Visitor}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::fmt; use std::marker::PhantomData; use crate::schema::*; #[derive(Clone, Debug)] pub enum RemovableValue<T: Clone> { Default, Remove, Specified(T), } impl<T: Clone> RemovableValue<T> { pub(crate) fn is_default(&self) -> bool { match self { RemovableValue::Default => true, _ => false, } } } impl<T: Clone> From<T> for RemovableValue<T> { fn from(value: T) -> Self { RemovableValue::Specified(value) } } macro_rules! from_into_with_removable{ ( $( $from:ty => $to:ty ),* $(,)? ) => { $( impl From<$from> for RemovableValue<$to> { fn from(v: $from) -> Self { RemovableValue::Specified(v.into()) } } )* }; } from_into_with_removable! { &str => String, SortOrder => Sort, EncodingSortField => Sort, Vec<SelectionInitIntervalElement> => Sort, DefWithConditionTextFieldDefValue => Tooltip, Vec<TextFieldDef> => Tooltip, bool => TooltipUnion, f64 => TooltipUnion, String => TooltipUnion, TooltipContent => TooltipUnion, } impl<T: Clone> Default for RemovableValue<T> { fn default() -> Self { RemovableValue::Default } } impl<T> Serialize for RemovableValue<T> where T: Serialize + Clone, { #[inline] fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match *self { RemovableValue::Specified(ref value) => serializer.serialize_some(value), RemovableValue::Default => serializer.serialize_none(), RemovableValue::Remove => serializer.serialize_none(), } } } struct RemovableValueVisitor<T> { marker: PhantomData<T>, } impl<'de, T> Visitor<'de> for RemovableValueVisitor<T> where T: Deserialize<'de> + Clone, { type Value = RemovableValue<T>; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("option") } #[inline] fn visit_unit<E>(self) -> Result<Self::Value, E> where E: Error, { Ok(RemovableValue::Remove) } #[inline] fn visit_none<E>(self) -> Result<Self::Value, E> where E: Error, { Ok(RemovableValue::Remove) } #[inline] fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { T::deserialize(deserializer).map(RemovableValue::Specified) } #[doc(hidden)] fn __private_visit_untagged_option<D>(self, deserializer: D) -> Result<Self::Value, ()> where D: Deserializer<'de>, { Ok(match T::deserialize(deserializer) { Ok(v) => RemovableValue::Specified(v), _ => RemovableValue::Remove, }) } } impl<'de, T> Deserialize<'de> for RemovableValue<T> where T: Deserialize<'de> + Clone, { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_option(RemovableValueVisitor { marker: PhantomData, }) } }
use serde::de::{Error, Visitor}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::fmt; use std::marker::PhantomData; use crate::schema::*; #[derive(Clone, Debug)] pub enum RemovableValue<T: Clone> { Default, Remove, Specified(T), } impl<T: Clone> RemovableValue<T> { pub(crate) fn is_default(&self) -> bool { match self { RemovableValue::Default => true, _ => false, } } } impl<T: Clone> From<T> for RemovableValue<T> { fn from(value: T) -> Self { RemovableValue::Specified(value) } } macro_rules! from_into_with_removable{ ( $( $from:ty => $to:ty ),* $(,)? ) => { $( impl From<$from> for RemovableValue<$to> { fn from(v: $from) -> Self { RemovableValue::Specified(v.into()) } } )* }; } from_into_with_removable! { &str => String, SortOrder => Sort, EncodingSortField => Sort, Vec<SelectionInitIntervalElement> => Sort, DefWithConditionTextFieldDefValue => Tooltip, Vec<TextFieldDef> => Tooltip, bool => TooltipUnion, f64 => TooltipUnion, String => TooltipUnion, TooltipContent => TooltipUnion, } impl<T: Clone> Default for RemovableValue<T> { fn default() -> Self { RemovableValue::Default } } impl<T> Serialize for RemovableValue<T> where T: Serialize + Clone, { #[inline] fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match *self { RemovableValue::Specified(ref value) => serializer.serialize_some(value), RemovableValue::Default => serializer.serialize_none(), RemovableValue::Remove => serializer.serialize_none(), } } } struct RemovableValueVisitor<T> { marker: PhantomData<T>, } impl<'de, T> Visitor<'de> for RemovableValueVisitor<T> where T: Deserialize<'de> + Clone, { type Value = RemovableValue<T>; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("option") } #[inline] fn visit_unit<E>(self) -> Result<Self::Value, E> where E: Error, { Ok(RemovableValue::Remove) } #[inline] fn visit_none<E>(self) -> Result<Self::Value, E> where E: Error, { Ok(RemovableValue::Remove) } #[inline] fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { T::deserialize(deserializer).map(RemovableValue::Specified) } #[doc(hidden)] fn __private_visit_untagged_option<D>(self, deserializer: D) -> Result<Self::Value, ()> where D: Deserializer<'de>, { Ok(match T::deserialize(deserializer) { Ok(v) => RemovableValue::Specified(v), _ => RemovableValue::Remove, }) } } impl<'de, T> Deserialize<'de> for RemovableValue<T> where T: Deserialize<'de> + Clone, {
}
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_option(RemovableValueVisitor { marker: PhantomData, }) }
function_block-full_function
[ { "content": "#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\n#[allow(unused)]\n\nenum UnusedInlineDataset {\n\n AnythingMap(HashMap<String, Option<serde_json::Value>>),\n\n Bool(bool),\n\n Double(f64),\n\n String(String),\n\n}\n\n\n\n/// Aggregation funct...
Rust
src/mv_backend/backend.rs
Kagamihime/matrix-visualisations
10c9612434ad835d12b5c164c82e8e8eb6545325
use std::sync::{Arc, RwLock}; use failure::{format_err, Error}; use serde_derive::{Deserialize, Serialize}; use serde_json::Value as JsonValue; use yew::callback::Callback; use yew::format::{Json, Nothing}; use yew::services::fetch::{FetchService, FetchTask, Request, Response, Uri}; use super::session::Session; pub struct MatrixVisualisationsBackend { fetch: FetchService, session: Arc<RwLock<Session>>, } #[derive(Debug, Deserialize, Serialize)] pub struct EventsResponse { pub events: Vec<JsonValue>, } impl MatrixVisualisationsBackend { pub fn with_session(session: Arc<RwLock<Session>>) -> Self { MatrixVisualisationsBackend { fetch: FetchService::new(), session, } } pub fn deepest(&mut self, callback: Callback<Result<EventsResponse, Error>>) -> FetchTask { let (server_name, room_id) = { let session = self.session.read().unwrap(); (session.server_name.clone(), session.room_id.clone()) }; let uri = Uri::builder() .scheme("https") .authority(server_name.as_str()) .path_and_query(format!("/visualisations/deepest/{}", room_id).as_str()) .build() .expect("Failed to build URI."); self.request(callback, uri) } pub fn ancestors( &mut self, callback: Callback<Result<EventsResponse, Error>>, from: &[String], ) -> FetchTask { let (server_name, room_id) = { let session = self.session.read().unwrap(); (session.server_name.clone(), session.room_id.clone()) }; let events_list = from.join(","); let uri = Uri::builder() .scheme("https") .authority(server_name.as_str()) .path_and_query( format!( "/visualisations/ancestors/{}?from={}&limit=10", room_id, events_list ) .as_str(), ) .build() .expect("Failed to build URI."); self.request(callback, uri) } pub fn descendants( &mut self, callback: Callback<Result<EventsResponse, Error>>, from: &[String], ) -> FetchTask { let (server_name, room_id) = { let session = self.session.read().unwrap(); (session.server_name.clone(), session.room_id.clone()) }; let events_list = from.join(","); let uri = Uri::builder() .scheme("https") .authority(server_name.as_str()) .path_and_query( format!( "/visualisations/descendants/{}?from={}&limit=10", room_id, events_list ) .as_str(), ) .build() .expect("Failed to build URI."); self.request(callback, uri) } pub fn state( &mut self, callback: Callback<Result<EventsResponse, Error>>, from: &str, ) -> FetchTask { let (server_name, room_id) = { let session = self.session.read().unwrap(); (session.server_name.clone(), session.room_id.clone()) }; let uri = Uri::builder() .scheme("https") .authority(server_name.as_str()) .path_and_query(format!("/visualisations/state/{}?from={}", room_id, from).as_str()) .build() .expect("Failed to build URI."); self.request(callback, uri) } pub fn stop(&mut self, callback: Callback<Result<(), Error>>) -> FetchTask { let (server_name, room_id) = { let session = self.session.read().unwrap(); (session.server_name.clone(), session.room_id.clone()) }; let uri = Uri::builder() .scheme("https") .authority(server_name.as_str()) .path_and_query(format!("/visualisations/stop/{}", room_id).as_str()) .build() .expect("Failed to build URI."); let request = Request::get(uri) .header("Content-Type", "application/json") .body(Nothing) .expect("Failed to buid request."); let handler = move |response: Response<Nothing>| { let (meta, _) = response.into_parts(); if meta.status.is_success() { callback.emit(Ok(())) } else { callback.emit(Err(format_err!( "{}: error stopping the backend", meta.status ))) } }; self.fetch.fetch(request, handler.into()) } fn request( &mut self, callback: Callback<Result<EventsResponse, Error>>, uri: Uri, ) -> FetchTask { let request = Request::get(uri) .header("Content-Type", "application/json") .body(Nothing) .expect("Failed to buid request."); let handler = move |response: Response<Json<Result<EventsResponse, Error>>>| { let (meta, Json(data)) = response.into_parts(); if meta.status.is_success() { callback.emit(data) } else { callback.emit(Err(format_err!("{}: error fetching events", meta.status))) } }; self.fetch.fetch(request, handler.into()) } }
use std::sync::{Arc, RwLock}; use failure::{format_err, Error}; use serde_derive::{Deserialize, Serialize}; use serde_json::Value as JsonValue; use yew::callback::Callback; use yew::format::{Json, Nothing}; use yew::services::fetch::{FetchService, FetchTask, Request, Response, Uri}; use super::session::Session; pub struct MatrixVisualisationsBackend { fetch: FetchService, session: Arc<RwLock<Session>>, } #[derive(Debug, Deserialize, Serialize)] pub struct EventsResponse { pub events: Vec<JsonValue>, } impl MatrixVisualisationsBackend { pub fn with_session(session: Arc<RwLock<Session>>) -> Self { MatrixVisualisationsBackend { fetch: FetchService::new(), session, } } pub fn deepest(&mut self, callback: Callback<Result<EventsResponse, Error>>) -> FetchTask { let (server_name, room_id) = { let session = self.session.read().unwrap(); (session.server_name.clone(), session.room_id.clone()) }; let uri = Uri::builder() .scheme("https") .authority(server_name.as_str()) .path_and_query(format!("/visualisations/deepest/{}", room_id).as_str()) .build() .expect("Failed to build URI."); self.request(callback, uri) } pub fn ancestors( &mut self, callback: Callback<Result<EventsResponse, Error>>, from: &[String], ) -> FetchTask { let (server_name, room_id) = { let session = self.session.read().unwrap(); (session.server_name.clone(), session.room_id.clone()) }; let events_list = from.join(","); let uri = Uri::builder() .scheme("https") .authority(server_name.as_str()) .path_and_query( format!( "/visualisations/ancestors/{}?from={}&limit=10", room_id, events_list ) .as_str(), ) .build() .expect("Failed to build URI."); self.request(callback, uri) } pub fn descendants( &mut self, callback: Callback<Result<EventsResponse, Error>>, from: &[String], ) -> FetchTask { let (server_name, room_id) = { let session = self.session.read().unwrap(); (session.server_name.clone(), session.room_id.clone()) }; let events_list = from.join(","); let uri = Uri::builder() .scheme("https") .authority(server_name.as_str()) .path_and_query( format!( "/visualisations/descendants/{}?from={}&limit=10", room_id, events_list ) .as_str(), ) .build() .expect("Failed to build URI."); self.request(callback, uri) } pub fn state( &mut self, callback: Callback<Result<EventsResponse, Error>>, from: &str, ) -> FetchTask { let (server_name, room_id) = { let session = self.session.read().unwrap(); (session.server_name.clone(), session.room_id.clone()) }; let uri = Uri::builder() .scheme("https") .authority(server_name.as_str()) .path_and_query(format!("/visualisations/state/{}?from={}", room_id, from).as_str()) .build() .expect("Failed to build URI."); self.request(callback, uri) } pub fn stop(&mut self, callback: Callback<Result<(), Error>>) -> FetchTask { let (server_name, room_id) = { let session = self.session.read().unwrap(); (session.server_name.clone(), session.room_id.clone()) }; let uri = Uri::builder() .scheme("https") .authority(server_name.as_str()) .path_and_query(format!("/visualisations/stop/{}", room_id).as_str()) .build() .expect("Failed to build URI."); let request = Request::get(uri) .header("Content-Type", "application/json") .body(Nothing) .expect("Failed to buid request."); let handler = move |response: Response<Nothing>| { let (meta, _) = response.into_parts(); if meta.status.is_success() { callback.emit(Ok(())) } else { callback.emit(
) } }; self.fetch.fetch(request, handler.into()) } fn request( &mut self, callback: Callback<Result<EventsResponse, Error>>, uri: Uri, ) -> FetchTask { let request = Request::get(uri) .header("Content-Type", "application/json") .body(Nothing) .expect("Failed to buid request."); let handler = move |response: Response<Json<Result<EventsResponse, Error>>>| { let (meta, Json(data)) = response.into_parts(); if meta.status.is_success() { callback.emit(data) } else { callback.emit(Err(format_err!("{}: error fetching events", meta.status))) } }; self.fetch.fetch(request, handler.into()) } }
Err(format_err!( "{}: error stopping the backend", meta.status ))
call_expression
[ { "content": "// Builds a filter which allows the application to get events in the federation format with only\n\n// the fields required to observe the room. Events in the federation format includes informations\n\n// like the depth of the event in the DAG and the ID of the previous events, it allows the\n\n// ...
Rust
src/encode.rs
yancyribbens/rust-elements
df7e3cf0d5507bd47be0d5e5a4ba680a778b78ac
use std::io::Cursor; use std::{error, fmt, io, mem}; use ::bitcoin::consensus::encode as btcenc; use transaction::{Transaction, TxIn, TxOut}; pub use ::bitcoin::consensus::encode::MAX_VEC_SIZE; #[derive(Debug)] pub enum Error { Bitcoin(btcenc::Error), OversizedVectorAllocation { requested: usize, max: usize, }, ParseFailed(&'static str), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::Bitcoin(ref e) => write!(f, "a Bitcoin type encoding error: {}", e), Error::OversizedVectorAllocation { requested: ref r, max: ref m, } => write!(f, "oversized vector allocation: requested {}, maximum {}", r, m), Error::ParseFailed(ref e) => write!(f, "parse failed: {}", e), } } } impl error::Error for Error { fn cause(&self) -> Option<&error::Error> { match *self { Error::Bitcoin(ref e) => Some(e), _ => None, } } fn description(&self) -> &str { "an Elements encoding error" } } #[doc(hidden)] impl From<btcenc::Error> for Error { fn from(e: btcenc::Error) -> Error { Error::Bitcoin(e) } } pub trait Encodable { fn consensus_encode<W: io::Write>(&self, e: W) -> Result<usize, Error>; } pub trait Decodable: Sized { fn consensus_decode<D: io::Read>(d: D) -> Result<Self, Error>; } pub fn serialize<T: Encodable + ?Sized>(data: &T) -> Vec<u8> { let mut encoder = Cursor::new(vec![]); data.consensus_encode(&mut encoder).unwrap(); encoder.into_inner() } pub fn serialize_hex<T: Encodable + ?Sized>(data: &T) -> String { ::bitcoin::hashes::hex::ToHex::to_hex(&serialize(data)[..]) } pub fn deserialize<'a, T: Decodable>(data: &'a [u8]) -> Result<T, Error> { let (rv, consumed) = deserialize_partial(data)?; } pub fn deserialize_partial<'a, T: Decodable>(data: &'a [u8]) -> Result<(T, usize), Error> { let mut decoder = Cursor::new(data); let rv = Decodable::consensus_decode(&mut decoder)?; let consumed = decoder.position() as usize; Ok((rv, consumed)) } macro_rules! impl_upstream { ($type: ty) => { impl Encodable for $type { fn consensus_encode<W: io::Write>(&self, mut e: W) -> Result<usize, Error> { Ok(btcenc::Encodable::consensus_encode(self, &mut e)?) } } impl Decodable for $type { fn consensus_decode<D: io::Read>(mut d: D) -> Result<Self, Error> { Ok(btcenc::Decodable::consensus_decode(&mut d)?) } } }; } impl_upstream!(u8); impl_upstream!(u32); impl_upstream!(u64); impl_upstream!([u8; 32]); impl_upstream!(Vec<u8>); impl_upstream!(Vec<Vec<u8>>); impl_upstream!(btcenc::VarInt); impl_upstream!(::bitcoin::blockdata::script::Script); impl_upstream!(::bitcoin::hashes::sha256d::Hash); macro_rules! impl_vec { ($type: ty) => { impl Encodable for Vec<$type> { #[inline] fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, Error> { let mut len = 0; len += btcenc::VarInt(self.len() as u64).consensus_encode(&mut s)?; for c in self.iter() { len += c.consensus_encode(&mut s)?; } Ok(len) } } impl Decodable for Vec<$type> { #[inline] fn consensus_decode<D: io::Read>(mut d: D) -> Result<Self, Error> { let len = btcenc::VarInt::consensus_decode(&mut d)?.0; let byte_size = (len as usize) .checked_mul(mem::size_of::<$type>()) .ok_or(self::Error::ParseFailed("Invalid length"))?; if byte_size > MAX_VEC_SIZE { return Err(self::Error::OversizedVectorAllocation { requested: byte_size, max: MAX_VEC_SIZE, }); } let mut ret = Vec::with_capacity(len as usize); for _ in 0..len { ret.push(Decodable::consensus_decode(&mut d)?); } Ok(ret) } } }; } impl_vec!(TxIn); impl_vec!(TxOut); impl_vec!(Transaction);
use std::io::Cursor; use std::{error, fmt, io, mem}; use ::bitcoin::consensus::encode as btcenc; use transaction::{Transaction, TxIn, TxOut}; pub use ::bitcoin::consensus::encode::MAX_VEC_SIZE; #[derive(Debug)] pub enum Error { Bitcoin(btcenc::Error), OversizedVectorAllocation { requested: usize, max: usize, }, ParseFailed(&'static str), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
} } impl error::Error for Error { fn cause(&self) -> Option<&error::Error> { match *self { Error::Bitcoin(ref e) => Some(e), _ => None, } } fn description(&self) -> &str { "an Elements encoding error" } } #[doc(hidden)] impl From<btcenc::Error> for Error { fn from(e: btcenc::Error) -> Error { Error::Bitcoin(e) } } pub trait Encodable { fn consensus_encode<W: io::Write>(&self, e: W) -> Result<usize, Error>; } pub trait Decodable: Sized { fn consensus_decode<D: io::Read>(d: D) -> Result<Self, Error>; } pub fn serialize<T: Encodable + ?Sized>(data: &T) -> Vec<u8> { let mut encoder = Cursor::new(vec![]); data.consensus_encode(&mut encoder).unwrap(); encoder.into_inner() } pub fn serialize_hex<T: Encodable + ?Sized>(data: &T) -> String { ::bitcoin::hashes::hex::ToHex::to_hex(&serialize(data)[..]) } pub fn deserialize<'a, T: Decodable>(data: &'a [u8]) -> Result<T, Error> { let (rv, consumed) = deserialize_partial(data)?; } pub fn deserialize_partial<'a, T: Decodable>(data: &'a [u8]) -> Result<(T, usize), Error> { let mut decoder = Cursor::new(data); let rv = Decodable::consensus_decode(&mut decoder)?; let consumed = decoder.position() as usize; Ok((rv, consumed)) } macro_rules! impl_upstream { ($type: ty) => { impl Encodable for $type { fn consensus_encode<W: io::Write>(&self, mut e: W) -> Result<usize, Error> { Ok(btcenc::Encodable::consensus_encode(self, &mut e)?) } } impl Decodable for $type { fn consensus_decode<D: io::Read>(mut d: D) -> Result<Self, Error> { Ok(btcenc::Decodable::consensus_decode(&mut d)?) } } }; } impl_upstream!(u8); impl_upstream!(u32); impl_upstream!(u64); impl_upstream!([u8; 32]); impl_upstream!(Vec<u8>); impl_upstream!(Vec<Vec<u8>>); impl_upstream!(btcenc::VarInt); impl_upstream!(::bitcoin::blockdata::script::Script); impl_upstream!(::bitcoin::hashes::sha256d::Hash); macro_rules! impl_vec { ($type: ty) => { impl Encodable for Vec<$type> { #[inline] fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, Error> { let mut len = 0; len += btcenc::VarInt(self.len() as u64).consensus_encode(&mut s)?; for c in self.iter() { len += c.consensus_encode(&mut s)?; } Ok(len) } } impl Decodable for Vec<$type> { #[inline] fn consensus_decode<D: io::Read>(mut d: D) -> Result<Self, Error> { let len = btcenc::VarInt::consensus_decode(&mut d)?.0; let byte_size = (len as usize) .checked_mul(mem::size_of::<$type>()) .ok_or(self::Error::ParseFailed("Invalid length"))?; if byte_size > MAX_VEC_SIZE { return Err(self::Error::OversizedVectorAllocation { requested: byte_size, max: MAX_VEC_SIZE, }); } let mut ret = Vec::with_capacity(len as usize); for _ in 0..len { ret.push(Decodable::consensus_decode(&mut d)?); } Ok(ret) } } }; } impl_vec!(TxIn); impl_vec!(TxOut); impl_vec!(Transaction);
match *self { Error::Bitcoin(ref e) => write!(f, "a Bitcoin type encoding error: {}", e), Error::OversizedVectorAllocation { requested: ref r, max: ref m, } => write!(f, "oversized vector allocation: requested {}, maximum {}", r, m), Error::ParseFailed(ref e) => write!(f, "parse failed: {}", e), }
if_condition
[ { "content": "/// Decode a bech32 string into the raw HRP and the data bytes.\n\n/// The HRP is returned as it was found in the original string,\n\n/// so it can be either lower or upper case.\n\npub fn decode(s: &str) -> Result<(&str, Vec<u5>), Error> {\n\n // Ensure overall length is within bounds\n\n l...
Rust
src/main.rs
sifyfy/docker-rp
8562b0193a1cb907f25749142ccf7ec08a4af260
#[macro_use] extern crate log; pub mod conf { use failure::{format_err, ResultExt}; use glob::glob; use serde_derive::{Deserialize, Serialize}; use std::path::PathBuf; use structopt::StructOpt; use url::Url; #[derive(Debug, StructOpt)] #[structopt(rename_all = "kebab-case")] pub struct Args { #[structopt( short, long, help = "listen address, such as 0.0.0.0, 127.0.0.1, 192.168.1.2" )] pub host: Option<String>, #[structopt(short, long, help = "listen port")] pub port: Option<u16>, #[structopt(short, long, help = "virtual host. eg. localhost, example.com")] pub domain: Option<String>, #[structopt( short = "r", long, parse(try_from_str = "parse_reverse_proxy_mapping"), help = "eg. /path/to:http://localhost:3000/path/to" )] pub reverse_proxy: Vec<ReverseProxyMapping>, #[structopt( long, parse(from_os_str), help = "a nginx conf file path to which this will write out" )] pub nginx_conf: Option<PathBuf>, #[structopt( long, default_value = "/conf", parse(from_str = "parse_path_without_trailing_slash") )] pub config_dir: PathBuf, #[structopt(flatten)] pub verbose: clap_verbosity_flag::Verbosity, } impl Args { pub fn from_args() -> Args { <Args as StructOpt>::from_args() } } pub fn parse_reverse_proxy_mapping(s: &str) -> Result<ReverseProxyMapping, failure::Error> { ReverseProxyMapping::parse(s) } pub fn parse_path_without_trailing_slash(s: &str) -> PathBuf { PathBuf::from(s.trim_end_matches("/")) } #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Serialize, Deserialize)] pub struct ReverseProxyMapping { pub path: String, #[serde(with = "url_serde")] pub url: Url, } impl ReverseProxyMapping { pub fn parse(s: &str) -> Result<ReverseProxyMapping, failure::Error> { let i = s .find(":") .ok_or_else(|| format_err!("missing separator ':' in {}", s))?; let (path, url) = s.split_at(i); let url = url.trim_start_matches(":"); Ok(ReverseProxyMapping { path: path.into(), url: Url::parse(url) .with_context(|_| format!("Failed to parse as URL: {}", url.to_owned()))?, }) } } #[derive(Debug, Clone, Serialize, Deserialize)] struct RawAppConfig { host: Option<String>, port: Option<u16>, domain: Option<String>, #[serde(default)] reverse_proxy: Vec<ReverseProxyMapping>, nginx_conf: Option<PathBuf>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AppConfig { pub host: String, pub port: u16, pub domain: Option<String>, #[serde(default)] pub reverse_proxy: Vec<ReverseProxyMapping>, pub nginx_conf: PathBuf, } impl AppConfig { pub fn from_args_and_config(args: Args) -> Result<AppConfig, failure::Error> { let mut settings = config::Config::default(); let config_dir = format!("{}/*", args.config_dir.display()); debug!("config_dir: {}", config_dir); settings.merge( glob(&config_dir)? .map(|path| { path.map(|path| { info!("load config file: {}", path.display()); config::File::from(path) }) }) .collect::<Result<Vec<_>, _>>()?, )?; trace!("settings: {:#?}", settings); let RawAppConfig { host: rac_host, port: rac_port, domain: rac_domain, reverse_proxy: rac_reverse_proxy, nginx_conf: rac_nginx_conf, } = { let raw_app_config = settings.try_into()?; debug!("raw_app_config: {:#?}", raw_app_config); raw_app_config }; let Args { host: args_host, port: args_port, domain: args_domain, reverse_proxy: args_reverse_proxy, nginx_conf: args_nginx_conf, config_dir: _, verbose: _, } = args; Ok(AppConfig { host: args_host.or(rac_host).unwrap_or_else(|| "0.0.0.0".into()), port: args_port.or(rac_port).unwrap_or(10080), domain: args_domain.or(rac_domain), reverse_proxy: args_reverse_proxy .into_iter() .chain(rac_reverse_proxy.into_iter()) .collect(), nginx_conf: args_nginx_conf .or(rac_nginx_conf) .unwrap_or_else(|| PathBuf::from("/etc/nginx/conf.d/default.conf")), }) } } #[cfg(test)] mod test { use super::*; #[test] fn config_dir_default_not_specified() { use structopt::StructOpt; let cli_args: &[&str] = &["test"]; let args = Args::from_iter_safe(cli_args.iter()).unwrap(); assert_eq!( "/conf".to_string(), format!("{}", args.config_dir.display()) ); } #[test] fn config_dir_default_omit_value() { use structopt::StructOpt; let cli_args: &[&str] = &["test", "--config-dir"]; let args = Args::from_iter_safe(cli_args.iter()).unwrap(); assert_eq!( "/conf".to_string(), format!("{}", args.config_dir.display()) ); } #[test] fn config_dir_custom_relative_path() { use structopt::StructOpt; let cli_args: &[&str] = &["test", "--config-dir", "./conf"]; let args = Args::from_iter_safe(cli_args.iter()).unwrap(); assert_eq!( "./conf".to_string(), format!("{}", args.config_dir.display()) ); } #[test] fn config_dir_custom_absolute_path() { use structopt::StructOpt; let cli_args: &[&str] = &["test", "--config-dir", "/path/to/conf"]; let args = Args::from_iter_safe(cli_args.iter()).unwrap(); assert_eq!( "/path/to/conf".to_string(), format!("{}", args.config_dir.display()) ); } #[test] fn config_dir_custom_relative_path_with_trailing_slash() { use structopt::StructOpt; let cli_args: &[&str] = &["test", "--config-dir", "./conf/"]; let args = Args::from_iter_safe(cli_args.iter()).unwrap(); assert_eq!( "./conf".to_string(), format!("{}", args.config_dir.display()) ); } #[test] fn config_dir_custom_absolute_path_with_trailing_slash() { use structopt::StructOpt; let cli_args: &[&str] = &["test", "--config-dir", "/path/to/conf/"]; let args = Args::from_iter_safe(cli_args.iter()).unwrap(); assert_eq!( "/path/to/conf".to_string(), format!("{}", args.config_dir.display()) ); } #[test] fn nginx_conf_path_default_args() { use structopt::StructOpt; let cli_args: &[&str] = &["test"]; let args = Args::from_iter_safe(cli_args.iter()).unwrap(); assert_eq!(None, args.nginx_conf); } #[test] fn nginx_conf_path_custom_args() { use structopt::StructOpt; let cli_args: &[&str] = &["test", "--nginx-conf", "/etc/nginx/conf.d/custom.conf"]; let args = Args::from_iter_safe(cli_args.iter()).unwrap(); assert_eq!( Some(PathBuf::from("/etc/nginx/conf.d/custom.conf")), args.nginx_conf ); } #[test] #[should_panic(expected = "--nginx-conf without value")] fn nginx_conf_path_empty_args() { use structopt::StructOpt; let cli_args: &[&str] = &["test", "--nginx-conf"]; Args::from_iter_safe(cli_args.iter()).expect("--nginx-conf without value"); } #[test] fn nginx_conf_path_default_app_config() { use structopt::StructOpt; let cli_args: &[&str] = &["test"]; let args = Args::from_iter_safe(cli_args.iter()).unwrap(); let app_config = AppConfig::from_args_and_config(args).unwrap(); assert_eq!( PathBuf::from("/etc/nginx/conf.d/default.conf"), app_config.nginx_conf ); } #[test] fn nginx_conf_path_custom_app_config() { use structopt::StructOpt; let cli_args: &[&str] = &["test", "--config-dir", "./tests/conf_nginx_dir"]; let args = Args::from_iter_safe(cli_args.iter()).unwrap(); let app_config = AppConfig::from_args_and_config(args).unwrap(); assert_eq!( PathBuf::from("./tmp/nginx_default.conf"), app_config.nginx_conf ); } } } use failure::ResultExt; use std::fs; use std::io::{self, Write}; fn main() -> Result<(), exitfailure::ExitFailure> { let args = conf::Args::from_args(); env_logger::builder() .filter_level(args.verbose.log_level().to_level_filter()) .init(); debug!("args: {:#?}", args); let app_config = conf::AppConfig::from_args_and_config(args).context("Load config")?; debug!("app_config: {:#?}", app_config); let mut writer = io::BufWriter::new( fs::File::create(app_config.nginx_conf.as_path()) .with_context(|err| format!("{}: {}", err, app_config.nginx_conf.display()))?, ); write!( writer, "{}", render_nginx_conf( &app_config.host, app_config.port, app_config.domain.as_ref().map(|s| s.as_str()), &app_config.reverse_proxy ) )?; Ok(()) } pub fn render_nginx_conf( host: &str, port: u16, domain: Option<&str>, reverse_proxy_mappings: &[conf::ReverseProxyMapping], ) -> String { let reverse_proxy_locations = reverse_proxy_mappings .iter() .fold(String::new(), |mut buf, rp| { buf.push_str(&format!( r#" location {} {{ proxy_pass {}; }} "#, rp.path, rp.url )); buf }); let conf = format!( r#" server {{ listen {}:{}; server_name {}; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Host $http_host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; {} }} "#, host, port, domain.unwrap_or("localhost"), reverse_proxy_locations, ); conf }
#[macro_use] extern crate log; pub mod conf { use failure::{format_err, ResultExt}; use glob::glob; use serde_derive::{Deserialize, Serialize}; use std::path::PathBuf; use structopt::StructOpt; use url::Url; #[derive(Debug, StructOpt)] #[structopt(rename_all = "kebab-case")] pub struct Args { #[structopt( short, long, help = "listen address, such as 0.0.0.0, 127.0.0.1, 192.168.1.2" )] pub host: Option<String>, #[structopt(short, long, help = "listen port")] pub port: Option<u16>, #[structopt(short, long, help = "virtual host. eg. localhost, example.com")] pub domain: Option<String>, #[structopt( short = "r", long, parse(try_from_str = "parse_reverse_proxy_mapping"), help = "eg. /path/to:http://localhost:3000/path/to" )] pub reverse_proxy: Vec<ReverseProxyMapping>, #[structopt( long, parse(from_os_str), help = "a nginx conf file path to which this will write out" )] pub nginx_conf: Option<PathBuf>, #[structopt( long, default_value = "/conf", parse(from_str = "parse_path_without_trailing_slash") )] pub config_dir: PathBuf, #[structopt(flatten)] pub verbose: clap_verbosity_flag::Verbosity, } impl Args { pub fn from_args() -> Args { <Args as StructOpt>::from_args() } } pub fn parse_reverse_proxy_mapping(s: &str) -> Result<ReverseProxyMapping, failure::Error> { ReverseProxyMapping::parse(s) } pub fn parse_path_without_trailing_slash(s: &str) -> PathBuf { PathBuf::from(s.trim_end_matches("/")) } #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Serialize, Deserialize)] pub struct ReverseProxyMapping { pub path: String, #[serde(with = "url_serde")] pub url: Url, } impl ReverseProxyMapping { pub fn parse(s: &str) -> Result<ReverseProxyMapping, failure::Error> { let i = s .find(":") .ok_or_else(|| format_err!("missing separator ':' in {}", s))?; let (path, url) = s.split_at(i); let url = url.trim_start_matches(":"); Ok(ReverseProxyMapping { path: path.into(), url: Url::parse(url) .with_context(|_| format!("Failed to parse as URL: {}", url.to_owned()))?, }) } } #[derive(Debug, Clone, Serialize, Deserialize)] struct RawAppConfig { host: Option<String>, port: Option<u16>, domain: Option<String>, #[serde(default)] reverse_proxy: Vec<ReverseProxyMapping>, nginx_conf: Option<PathBuf>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AppConfig { pub host: String, pub port: u16, pub domain: Option<String>, #[serde(default)] pub reverse_proxy: Vec<ReverseProxyMapping>, pub nginx_conf: PathBuf, } impl AppConfig { pub fn from_args_and_config(args: Args) -> Result<AppConfig, failure::Error> { let mut settings = config::Config::default(); let config_dir = format!("{}/*", args.config_dir.display()); debug!("config_dir: {}", config_dir); settings.merge( glob(&config_dir)? .map(|path| { path.map(|path| { info!("load config file: {}", path.display()); config::File::from(path) }) }) .collect::<Result<Vec<_>, _>>()?, )?; trace!("settings: {:#?}", settings); let RawAppConfig { host: rac_host, port: rac_port, domain: rac_domain, reverse_proxy: rac_reverse_proxy, nginx_conf: rac_nginx_conf, } = { let raw_app_config = settings.try_into()?; debug!("raw_app_config: {:#?}", raw_app_config); raw_app_config }; let Args { host: args_host, port: args_port, domain: args_domain, reverse_proxy: args_reverse_proxy, nginx_conf: args_nginx_conf, config_dir: _, verbose: _, } = args; Ok(AppConfig { host: args_host.or(rac_host).unwrap_or_else(|| "0.0.0.0".into()), port: args_port.or(rac_port).unwrap_or(10080), domain: args_domain.or(rac_domain), reverse_proxy: args_reverse_proxy .into_iter() .chain(rac_reverse_proxy.into_iter()) .collect(), nginx_conf: args_nginx_conf .or(rac_nginx_conf) .unwrap_or_else(|| PathBuf::from("/etc/nginx/conf.d/default.conf")), }) } } #[cfg(test)] mod test { use super::*; #[test] fn config_dir_default_not_specified() { use structopt::StructOpt; let cli_args: &[&str] = &["test"]; let args = Args::from_iter_safe(cli_args.iter()).unwrap(); assert_eq!( "/conf".to_string(), format!("{}", args.config_dir.display()) ); } #[test] fn config_dir_default_omit_value() { use structopt::StructOpt; let cli_args: &[&str] = &["test", "--config-dir"]; let args = Args::from_iter_safe(cli_args.iter()).unwrap(); assert_eq!( "/conf".to_string(), format!("{}", args.config_dir.display()) ); } #[test]
#[test] fn config_dir_custom_absolute_path() { use structopt::StructOpt; let cli_args: &[&str] = &["test", "--config-dir", "/path/to/conf"]; let args = Args::from_iter_safe(cli_args.iter()).unwrap(); assert_eq!( "/path/to/conf".to_string(), format!("{}", args.config_dir.display()) ); } #[test] fn config_dir_custom_relative_path_with_trailing_slash() { use structopt::StructOpt; let cli_args: &[&str] = &["test", "--config-dir", "./conf/"]; let args = Args::from_iter_safe(cli_args.iter()).unwrap(); assert_eq!( "./conf".to_string(), format!("{}", args.config_dir.display()) ); } #[test] fn config_dir_custom_absolute_path_with_trailing_slash() { use structopt::StructOpt; let cli_args: &[&str] = &["test", "--config-dir", "/path/to/conf/"]; let args = Args::from_iter_safe(cli_args.iter()).unwrap(); assert_eq!( "/path/to/conf".to_string(), format!("{}", args.config_dir.display()) ); } #[test] fn nginx_conf_path_default_args() { use structopt::StructOpt; let cli_args: &[&str] = &["test"]; let args = Args::from_iter_safe(cli_args.iter()).unwrap(); assert_eq!(None, args.nginx_conf); } #[test] fn nginx_conf_path_custom_args() { use structopt::StructOpt; let cli_args: &[&str] = &["test", "--nginx-conf", "/etc/nginx/conf.d/custom.conf"]; let args = Args::from_iter_safe(cli_args.iter()).unwrap(); assert_eq!( Some(PathBuf::from("/etc/nginx/conf.d/custom.conf")), args.nginx_conf ); } #[test] #[should_panic(expected = "--nginx-conf without value")] fn nginx_conf_path_empty_args() { use structopt::StructOpt; let cli_args: &[&str] = &["test", "--nginx-conf"]; Args::from_iter_safe(cli_args.iter()).expect("--nginx-conf without value"); } #[test] fn nginx_conf_path_default_app_config() { use structopt::StructOpt; let cli_args: &[&str] = &["test"]; let args = Args::from_iter_safe(cli_args.iter()).unwrap(); let app_config = AppConfig::from_args_and_config(args).unwrap(); assert_eq!( PathBuf::from("/etc/nginx/conf.d/default.conf"), app_config.nginx_conf ); } #[test] fn nginx_conf_path_custom_app_config() { use structopt::StructOpt; let cli_args: &[&str] = &["test", "--config-dir", "./tests/conf_nginx_dir"]; let args = Args::from_iter_safe(cli_args.iter()).unwrap(); let app_config = AppConfig::from_args_and_config(args).unwrap(); assert_eq!( PathBuf::from("./tmp/nginx_default.conf"), app_config.nginx_conf ); } } } use failure::ResultExt; use std::fs; use std::io::{self, Write}; fn main() -> Result<(), exitfailure::ExitFailure> { let args = conf::Args::from_args(); env_logger::builder() .filter_level(args.verbose.log_level().to_level_filter()) .init(); debug!("args: {:#?}", args); let app_config = conf::AppConfig::from_args_and_config(args).context("Load config")?; debug!("app_config: {:#?}", app_config); let mut writer = io::BufWriter::new( fs::File::create(app_config.nginx_conf.as_path()) .with_context(|err| format!("{}: {}", err, app_config.nginx_conf.display()))?, ); write!( writer, "{}", render_nginx_conf( &app_config.host, app_config.port, app_config.domain.as_ref().map(|s| s.as_str()), &app_config.reverse_proxy ) )?; Ok(()) } pub fn render_nginx_conf( host: &str, port: u16, domain: Option<&str>, reverse_proxy_mappings: &[conf::ReverseProxyMapping], ) -> String { let reverse_proxy_locations = reverse_proxy_mappings .iter() .fold(String::new(), |mut buf, rp| { buf.push_str(&format!( r#" location {} {{ proxy_pass {}; }} "#, rp.path, rp.url )); buf }); let conf = format!( r#" server {{ listen {}:{}; server_name {}; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Host $http_host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; {} }} "#, host, port, domain.unwrap_or("localhost"), reverse_proxy_locations, ); conf }
fn config_dir_custom_relative_path() { use structopt::StructOpt; let cli_args: &[&str] = &["test", "--config-dir", "./conf"]; let args = Args::from_iter_safe(cli_args.iter()).unwrap(); assert_eq!( "./conf".to_string(), format!("{}", args.config_dir.display()) ); }
function_block-full_function
[ { "content": "# rp\n\n\n\nA simple HTTP reverse proxy server for web development.\n\n\n\n## Usage\n\n\n\nSimple:\n\n\n\n~~~~shell\n\ndocker --rm -it --network host sifyfy/rp -- -r /path/to:http://localhost:3000/path/to\n\n~~~~\n\n\n\nMultiple settings:\n\n\n\n~~~~shell\n\ndocker --rm -it --network host sifyfy/r...
Rust
relayer-cli/src/commands/query/client.rs
interchainio/ibc-rs
194a1714cf9dc807dd7b4e33726319293848dc58
use abscissa_core::clap::Parser; use abscissa_core::{Command, Runnable}; use tracing::debug; use ibc_relayer::chain::handle::ChainHandle; use ibc_relayer::chain::requests::{ HeightQuery, IncludeProof, PageRequest, QueryClientConnectionsRequest, QueryClientStateRequest, QueryConsensusStateRequest, QueryConsensusStatesRequest, }; use ibc::core::ics02_client::client_consensus::QueryClientEventRequest; use ibc::core::ics02_client::client_state::ClientState; use ibc::core::ics24_host::identifier::ChainId; use ibc::core::ics24_host::identifier::ClientId; use ibc::events::WithBlockDataType; use ibc::query::QueryTxRequest; use ibc::Height; use crate::application::app_config; use crate::cli_utils::spawn_chain_runtime; use crate::conclude::{exit_with_unrecoverable_error, Output}; #[derive(Clone, Command, Debug, Parser)] pub struct QueryClientStateCmd { #[clap(required = true, help = "identifier of the chain to query")] chain_id: ChainId, #[clap(required = true, help = "identifier of the client to query")] client_id: ClientId, #[clap(short = 'H', long, help = "the chain height context for the query")] height: Option<u64>, } impl Runnable for QueryClientStateCmd { fn run(&self) { let config = app_config(); let chain = spawn_chain_runtime(&config, &self.chain_id) .unwrap_or_else(exit_with_unrecoverable_error); match chain.query_client_state( QueryClientStateRequest { client_id: self.client_id.clone(), height: self.height.map_or(HeightQuery::Latest, |revision_height| { HeightQuery::Specific(ibc::Height::new(chain.id().version(), revision_height)) }), }, IncludeProof::No, ) { Ok((cs, _)) => Output::success(cs).exit(), Err(e) => Output::error(format!("{}", e)).exit(), } } } #[derive(Clone, Command, Debug, Parser)] pub struct QueryClientConsensusCmd { #[clap(required = true, help = "identifier of the chain to query")] chain_id: ChainId, #[clap(required = true, help = "identifier of the client to query")] client_id: ClientId, #[clap( short = 'c', long, help = "height of the client's consensus state to query" )] consensus_height: Option<u64>, #[clap(short = 's', long, help = "show only consensus heights")] heights_only: bool, #[clap( short = 'H', long, help = "the chain height context to be used, applicable only to a specific height" )] height: Option<u64>, } impl Runnable for QueryClientConsensusCmd { fn run(&self) { let config = app_config(); debug!("Options: {:?}", self); let chain = spawn_chain_runtime(&config, &self.chain_id) .unwrap_or_else(exit_with_unrecoverable_error); let counterparty_chain = match chain.query_client_state( QueryClientStateRequest { client_id: self.client_id.clone(), height: HeightQuery::Latest, }, IncludeProof::No, ) { Ok((cs, _)) => cs.chain_id(), Err(e) => Output::error(format!( "failed while querying client '{}' on chain '{}' with error: {}", self.client_id, self.chain_id, e )) .exit(), }; match self.consensus_height { Some(cs_height) => { let consensus_height = ibc::Height::new(counterparty_chain.version(), cs_height); let res = chain .query_consensus_state( QueryConsensusStateRequest { client_id: self.client_id.clone(), consensus_height, query_height: self.height.map_or( HeightQuery::Latest, |revision_height| { HeightQuery::Specific(ibc::Height::new( chain.id().version(), revision_height, )) }, ), }, IncludeProof::No, ) .map(|(consensus_state, _)| consensus_state); match res { Ok(cs) => Output::success(cs).exit(), Err(e) => Output::error(format!("{}", e)).exit(), } } None => { let res = chain.query_consensus_states(QueryConsensusStatesRequest { client_id: self.client_id.clone(), pagination: Some(PageRequest::all()), }); match res { Ok(states) => { if self.heights_only { let heights: Vec<Height> = states.iter().map(|cs| cs.height).collect(); Output::success(heights).exit() } else { Output::success(states).exit() } } Err(e) => Output::error(format!("{}", e)).exit(), } } } } } #[derive(Clone, Command, Debug, Parser)] pub struct QueryClientHeaderCmd { #[clap(required = true, help = "identifier of the chain to query")] chain_id: ChainId, #[clap(required = true, help = "identifier of the client to query")] client_id: ClientId, #[clap(required = true, help = "height of header to query")] consensus_height: u64, #[clap(short = 'H', long, help = "the chain height context for the query")] height: Option<u64>, } impl Runnable for QueryClientHeaderCmd { fn run(&self) { let config = app_config(); debug!("Options: {:?}", self); let chain = spawn_chain_runtime(&config, &self.chain_id) .unwrap_or_else(exit_with_unrecoverable_error); let counterparty_chain = match chain.query_client_state( QueryClientStateRequest { client_id: self.client_id.clone(), height: HeightQuery::Latest, }, IncludeProof::No, ) { Ok((cs, _)) => cs.chain_id(), Err(e) => Output::error(format!( "failed while querying client '{}' on chain '{}' with error: {}", self.client_id, self.chain_id, e )) .exit(), }; let consensus_height = ibc::Height::new(counterparty_chain.version(), self.consensus_height); let height = ibc::Height::new(chain.id().version(), self.height.unwrap_or(0_u64)); let res = chain.query_txs(QueryTxRequest::Client(QueryClientEventRequest { height, event_id: WithBlockDataType::UpdateClient, client_id: self.client_id.clone(), consensus_height, })); match res { Ok(header) => Output::success(header).exit(), Err(e) => Output::error(format!("{}", e)).exit(), } } } #[derive(Clone, Command, Debug, Parser)] pub struct QueryClientConnectionsCmd { #[clap(required = true, help = "identifier of the chain to query")] chain_id: ChainId, #[clap(required = true, help = "identifier of the client to query")] client_id: ClientId, #[clap( short = 'H', long, help = "the chain height which this query should reflect" )] height: Option<u64>, } impl Runnable for QueryClientConnectionsCmd { fn run(&self) { let config = app_config(); debug!("Options: {:?}", self); let chain = spawn_chain_runtime(&config, &self.chain_id) .unwrap_or_else(exit_with_unrecoverable_error); let res = chain.query_client_connections(QueryClientConnectionsRequest { client_id: self.client_id.clone(), }); match res { Ok(ce) => Output::success(ce).exit(), Err(e) => Output::error(format!("{}", e)).exit(), } } }
use abscissa_core::clap::Parser; use abscissa_core::{Command, Runnable}; use tracing::debug; use ibc_relayer::chain::handle::ChainHandle; use ibc_relayer::chain::requests::{ HeightQuery, IncludeProof, PageRequest, QueryClientConnectionsRequest, QueryClientStateRequest, QueryConsensusStateRequest, QueryConsensusStatesRequest, }; use ibc::core::ics02_client::client_consensus::QueryClientEventRequest; use ibc::core::ics02_client::client_state::ClientState; use ibc::core::ics24_host::identifier::ChainId; use ibc::core::ics24_host::identifier::ClientId; use ibc::events::WithBlockDataType; use ibc::query::QueryTxRequest; use ibc::Height; use crate::application::app_config; use crate::cli_utils::spawn_chain_runtime; use crate::conclude::{exit_with_unrecoverable_error, Output}; #[derive(Clone, Command, Debug, Parser)] pub struct QueryClientStateCmd { #[clap(required = true, help = "identifier of the chain to query")] chain_id: ChainId, #[clap(required = true, help = "identifier of the client to query")] client_id: ClientId, #[clap(short = 'H', long, help = "the chain height context for the query")] height: Option<u64>, } imp
ght" )] height: Option<u64>, } impl Runnable for QueryClientConsensusCmd { fn run(&self) { let config = app_config(); debug!("Options: {:?}", self); let chain = spawn_chain_runtime(&config, &self.chain_id) .unwrap_or_else(exit_with_unrecoverable_error); let counterparty_chain = match chain.query_client_state( QueryClientStateRequest { client_id: self.client_id.clone(), height: HeightQuery::Latest, }, IncludeProof::No, ) { Ok((cs, _)) => cs.chain_id(), Err(e) => Output::error(format!( "failed while querying client '{}' on chain '{}' with error: {}", self.client_id, self.chain_id, e )) .exit(), }; match self.consensus_height { Some(cs_height) => { let consensus_height = ibc::Height::new(counterparty_chain.version(), cs_height); let res = chain .query_consensus_state( QueryConsensusStateRequest { client_id: self.client_id.clone(), consensus_height, query_height: self.height.map_or( HeightQuery::Latest, |revision_height| { HeightQuery::Specific(ibc::Height::new( chain.id().version(), revision_height, )) }, ), }, IncludeProof::No, ) .map(|(consensus_state, _)| consensus_state); match res { Ok(cs) => Output::success(cs).exit(), Err(e) => Output::error(format!("{}", e)).exit(), } } None => { let res = chain.query_consensus_states(QueryConsensusStatesRequest { client_id: self.client_id.clone(), pagination: Some(PageRequest::all()), }); match res { Ok(states) => { if self.heights_only { let heights: Vec<Height> = states.iter().map(|cs| cs.height).collect(); Output::success(heights).exit() } else { Output::success(states).exit() } } Err(e) => Output::error(format!("{}", e)).exit(), } } } } } #[derive(Clone, Command, Debug, Parser)] pub struct QueryClientHeaderCmd { #[clap(required = true, help = "identifier of the chain to query")] chain_id: ChainId, #[clap(required = true, help = "identifier of the client to query")] client_id: ClientId, #[clap(required = true, help = "height of header to query")] consensus_height: u64, #[clap(short = 'H', long, help = "the chain height context for the query")] height: Option<u64>, } impl Runnable for QueryClientHeaderCmd { fn run(&self) { let config = app_config(); debug!("Options: {:?}", self); let chain = spawn_chain_runtime(&config, &self.chain_id) .unwrap_or_else(exit_with_unrecoverable_error); let counterparty_chain = match chain.query_client_state( QueryClientStateRequest { client_id: self.client_id.clone(), height: HeightQuery::Latest, }, IncludeProof::No, ) { Ok((cs, _)) => cs.chain_id(), Err(e) => Output::error(format!( "failed while querying client '{}' on chain '{}' with error: {}", self.client_id, self.chain_id, e )) .exit(), }; let consensus_height = ibc::Height::new(counterparty_chain.version(), self.consensus_height); let height = ibc::Height::new(chain.id().version(), self.height.unwrap_or(0_u64)); let res = chain.query_txs(QueryTxRequest::Client(QueryClientEventRequest { height, event_id: WithBlockDataType::UpdateClient, client_id: self.client_id.clone(), consensus_height, })); match res { Ok(header) => Output::success(header).exit(), Err(e) => Output::error(format!("{}", e)).exit(), } } } #[derive(Clone, Command, Debug, Parser)] pub struct QueryClientConnectionsCmd { #[clap(required = true, help = "identifier of the chain to query")] chain_id: ChainId, #[clap(required = true, help = "identifier of the client to query")] client_id: ClientId, #[clap( short = 'H', long, help = "the chain height which this query should reflect" )] height: Option<u64>, } impl Runnable for QueryClientConnectionsCmd { fn run(&self) { let config = app_config(); debug!("Options: {:?}", self); let chain = spawn_chain_runtime(&config, &self.chain_id) .unwrap_or_else(exit_with_unrecoverable_error); let res = chain.query_client_connections(QueryClientConnectionsRequest { client_id: self.client_id.clone(), }); match res { Ok(ce) => Output::success(ce).exit(), Err(e) => Output::error(format!("{}", e)).exit(), } } }
l Runnable for QueryClientStateCmd { fn run(&self) { let config = app_config(); let chain = spawn_chain_runtime(&config, &self.chain_id) .unwrap_or_else(exit_with_unrecoverable_error); match chain.query_client_state( QueryClientStateRequest { client_id: self.client_id.clone(), height: self.height.map_or(HeightQuery::Latest, |revision_height| { HeightQuery::Specific(ibc::Height::new(chain.id().version(), revision_height)) }), }, IncludeProof::No, ) { Ok((cs, _)) => Output::success(cs).exit(), Err(e) => Output::error(format!("{}", e)).exit(), } } } #[derive(Clone, Command, Debug, Parser)] pub struct QueryClientConsensusCmd { #[clap(required = true, help = "identifier of the chain to query")] chain_id: ChainId, #[clap(required = true, help = "identifier of the client to query")] client_id: ClientId, #[clap( short = 'c', long, help = "height of the client's consensus state to query" )] consensus_height: Option<u64>, #[clap(short = 's', long, help = "show only consensus heights")] heights_only: bool, #[clap( short = 'H', long, help = "the chain height context to be used, applicable only to a specific hei
random
[]
Rust
backend/services/keychain/src/main.rs
hiroaki-yamamoto/midas
7fa9c1d6605bead7e283b339639a89bb09ed6b1c
use ::std::convert::TryFrom; use ::std::net::SocketAddr; use ::clap::Parser; use ::futures::FutureExt; use ::futures::StreamExt; use ::http::StatusCode; use ::libc::{SIGINT, SIGTERM}; use ::mongodb::bson::{doc, oid::ObjectId}; use ::mongodb::Client; use ::nats::connect; use ::slog::Logger; use ::tokio::signal::unix as signal; use ::warp::Filter; use ::config::{CmdArgs, Config}; use ::csrf::{CSRFOption, CSRF}; use ::keychain::{APIKey, KeyChain}; use ::rpc::entities::{InsertOneResult, Status}; use ::rpc::keychain::ApiRename; use ::rpc::keychain::{ApiKey as RPCAPIKey, ApiKeyList as RPCAPIKeyList}; use ::rpc::rejection_handler::handle_rejection; macro_rules! declare_reject_func { () => { |e| { ::warp::reject::custom(Status::new( StatusCode::SERVICE_UNAVAILABLE, format!("{}", e), )) } }; } #[tokio::main] async fn main() { let opts: CmdArgs = CmdArgs::parse(); let config = Config::from_fpath(Some(opts.config)).unwrap(); let logger = config.build_slog(); let logger_in_handler = logger.clone(); let broker = connect(config.broker_url.as_str()).unwrap(); let db_cli = Client::with_uri_str(&config.db_url).await.unwrap(); let db = db_cli.database("midas"); let keychain = KeyChain::new(broker, db).await; let path_param = ::warp::any() .map(move || { return (keychain.clone(), logger_in_handler.clone()); }) .untuple_one(); let id_filter = ::warp::path::param().and_then(|id: String| async move { match ObjectId::parse_str(&id) { Err(_) => return Err(::warp::reject()), Ok(id) => return Ok(id), }; }); let get_handler = ::warp::get() .and(path_param.clone()) .and_then(|keychain: KeyChain, logger: Logger| async move { match keychain.list(doc! {}).await { Err(e) => { ::slog::warn!(logger, "An error was occured when querying: {}", e); return Err(::warp::reject()); } Ok(cursor) => { return Ok( cursor .map(|mut api_key| { api_key.inner_mut().prv_key = ("*").repeat(16); return api_key; }) .map(|api_key| { let api_key: Result<RPCAPIKey, String> = api_key.into(); return api_key; }) .filter_map(|api_key_result| async move { api_key_result.ok() }) .collect::<Vec<RPCAPIKey>>() .await, ); } }; }) .map(|api_key_list| { return ::warp::reply::json(&RPCAPIKeyList { keys: api_key_list }); }); let post_handler = ::warp::post() .and(path_param.clone()) .and(::warp::filters::body::json()) .and_then( |keychain: KeyChain, _: Logger, api_key: RPCAPIKey| async move { let api_key: APIKey = APIKey::try_from(api_key).map_err(declare_reject_func!())?; return keychain .push(api_key) .await .map_err(declare_reject_func!()) .map(|res| { let res: InsertOneResult = res.into(); return res; }); }, ) .map(|res: InsertOneResult| { return ::warp::reply::json(&res); }); let patch_handler = ::warp::patch() .and(path_param.clone()) .and(id_filter) .and(::warp::filters::body::json()) .and_then( |keychain: KeyChain, _: Logger, id: ObjectId, rename: ApiRename| async move { if let Err(_) = keychain.rename_label(id, &rename.label).await { return Err(::warp::reject()); }; return Ok(()); }, ) .untuple_one() .map(|| ::warp::reply()); let delete_handler = ::warp::delete() .and(path_param) .and(id_filter) .and_then(|keychain: KeyChain, _: Logger, id: ObjectId| async move { let del_defer = keychain.delete(id); if let Err(_) = del_defer.await { return Err(::warp::reject()); }; return Ok(()); }) .untuple_one() .map(|| ::warp::reply()); let route = CSRF::new(CSRFOption::builder()).protect().and( get_handler .or(post_handler) .or(patch_handler) .or(delete_handler) .recover(handle_rejection), ); let mut sig = signal::signal(signal::SignalKind::from_raw(SIGTERM | SIGINT)).unwrap(); let host: SocketAddr = config.host.parse().unwrap(); ::slog::info!(logger, "Opened REST server on {}", host); let (_, ws_svr) = ::warp::serve(route) .tls() .cert_path(&config.tls.cert) .key_path(&config.tls.prv_key) .bind_with_graceful_shutdown(host, async move { sig.recv().await; }); let svr = ws_svr.then(|_| async { ::slog::warn!(logger, "REST Server is shutting down! Bye! Bye!"); }); svr.await; }
use ::std::convert::TryFrom; use ::std::net::SocketAddr; use ::clap::Parser; use ::futures::FutureExt; use ::futures::StreamExt; use ::http::StatusCode; use ::libc::{SIGINT, SIGTERM}; use ::mongodb::bson::{doc, oid::ObjectId}; use ::mongodb::Client; use ::nats::connect; use ::slog::Logger; use ::tokio::signal::unix as signal; use ::warp::Filter; use ::config::{CmdArgs, Config}; use ::csrf::{CSRFOption, CSRF}; use ::keychain::{APIKey, KeyChain}; use ::rpc::entities::{InsertOneResult, Status}; use ::rpc::keychain::ApiRename; use ::rpc::keychain::{ApiKey as RPCAPIKey, ApiKeyList as RPCAPIKeyList}; use ::rpc::rejection_handler::handle_rejection; macro_rules! declare_reject_func { () => { |e| { ::warp::reject::custom(Status::new( StatusCode::SERVICE_UNAVAILABLE, format!("{}", e), )) } }; } #[tokio::main] async fn main() { let opts: CmdArgs = CmdArgs::parse(); let config = Config::from_fpath(Some(opts.config)).unwrap(); let logger = config.build_slog(); let logger_in_handler = logger.clone(); let broker = connect(config.broker_url.as_str()).unwrap(); let db_cli = Client::with_uri_str(&config.db_url).await.unwrap(); let db = db_cli.database("midas"); let keychain = KeyChain::new(broker, db).await; let path_param = ::warp::any() .map(move || { return (keychain.clone(), logger_in_handler.clone()); }) .untuple_one(); let id_filter = ::warp::path::param().and_then(|id: String| async move { match ObjectId::parse_str(&id) { Err(_) => return Err(::warp::reject()), Ok(id) => return Ok(id), }; }); let get_handler = ::warp::get() .and(path_param.clone()) .and_then(|keychain: KeyChain, logger: Logger| async move { match keychain.list(doc! {}).await { Err(e) => { ::slog::warn!(logger, "An error was occured when querying: {}", e); return Err(::warp::reject()); } Ok(cursor) => { return Ok( cursor .map(|mut api_key| { api_key.inner_mut().prv_key = ("*").repeat(16); return api_key; }) .map(|api_key| { let api_key: Result<RPCAPIKey, String> = api_key.into(); return api_key; }) .filter_map(|api_key_result| async move { api_key_result.ok() }) .collect::<Vec<RPCAPIKey>>() .await, ); } }; }) .map(|api_key_list| { return ::warp::reply::json(&RPCAPIKeyList { keys: api_key_list }); }); let post_handler = ::warp::post() .and(path_param.clone()) .and(::warp::filters::body::json()) .and_then( |keychain: KeyChain, _: Logger, api_key: RPCAPIKey| async move { let api_key: APIKey = APIKey::try_from(api_key).map_err(declare_reject_func!())?; return keychain .push(api_key) .await .map_err(declare_reject_func!()) .map(|res| { let res: InsertOneResult = res.into(); return res; }); }, ) .map(|res: InsertOneResult| { return ::warp::reply::json(&res); }); let patch_handler = ::warp::patch() .and(path_param.clone()) .and(id_filter) .
and(::warp::filters::body::json()) .and_then( |keychain: KeyChain, _: Logger, id: ObjectId, rename: ApiRename| async move { if let Err(_) = keychain.rename_label(id, &rename.label).await { return Err(::warp::reject()); }; return Ok(()); }, ) .untuple_one() .map(|| ::warp::reply()); let delete_handler = ::warp::delete() .and(path_param) .and(id_filter) .and_then(|keychain: KeyChain, _: Logger, id: ObjectId| async move { let del_defer = keychain.delete(id); if let Err(_) = del_defer.await { return Err(::warp::reject()); }; return Ok(()); }) .untuple_one() .map(|| ::warp::reply()); let route = CSRF::new(CSRFOption::builder()).protect().and( get_handler .or(post_handler) .or(patch_handler) .or(delete_handler) .recover(handle_rejection), ); let mut sig = signal::signal(signal::SignalKind::from_raw(SIGTERM | SIGINT)).unwrap(); let host: SocketAddr = config.host.parse().unwrap(); ::slog::info!(logger, "Opened REST server on {}", host); let (_, ws_svr) = ::warp::serve(route) .tls() .cert_path(&config.tls.cert) .key_path(&config.tls.prv_key) .bind_with_graceful_shutdown(host, async move { sig.recv().await; }); let svr = ws_svr.then(|_| async { ::slog::warn!(logger, "REST Server is shutting down! Bye! Bye!"); }); svr.await; }
function_block-function_prefixed
[ { "content": "fn main() {\n\n let mut protos = vec![];\n\n for proto in glob(\"../../../proto/**/*.proto\").unwrap() {\n\n let path = proto.unwrap();\n\n let path = String::from(path.to_str().unwrap());\n\n println!(\"cargo:rerun-if-changed={}\", path);\n\n protos.push(path);\n\n }\n\n return ::...
Rust
tests/support/server.rs
sgrif/reqwest
9f256405e57966de82a24f466d75604d2d2fafe2
use std::io::{Read, Write}; use std::net; use std::time::Duration; use std::sync::mpsc; use std::thread; pub struct Server { addr: net::SocketAddr, panic_rx: mpsc::Receiver<()>, } impl Server { pub fn addr(&self) -> net::SocketAddr { self.addr } } impl Drop for Server { fn drop(&mut self) { if !::std::thread::panicking() { self .panic_rx .recv_timeout(Duration::from_secs(3)) .expect("test server should not panic"); } } } #[derive(Debug, Default)] pub struct Txn { pub request: Vec<u8>, pub response: Vec<u8>, pub read_timeout: Option<Duration>, pub read_closes: bool, pub response_timeout: Option<Duration>, pub write_timeout: Option<Duration>, pub chunk_size: Option<usize>, } static DEFAULT_USER_AGENT: &'static str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")); pub fn spawn(txns: Vec<Txn>) -> Server { let listener = net::TcpListener::bind("127.0.0.1:0").unwrap(); let addr = listener.local_addr().unwrap(); let (panic_tx, panic_rx) = mpsc::channel(); let tname = format!("test({})-support-server", thread::current().name().unwrap_or("<unknown>")); thread::Builder::new().name(tname).spawn(move || { 'txns: for txn in txns { let mut expected = txn.request; let reply = txn.response; let (mut socket, _addr) = listener.accept().unwrap(); socket.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); replace_expected_vars(&mut expected, addr.to_string().as_ref(), DEFAULT_USER_AGENT.as_ref()); if let Some(dur) = txn.read_timeout { thread::park_timeout(dur); } let mut buf = vec![0; expected.len() + 256]; let mut n = 0; while n < expected.len() { match socket.read(&mut buf[n..]) { Ok(0) => { if !txn.read_closes { panic!("server unexpected socket closed"); } else { continue 'txns; } }, Ok(nread) => n += nread, Err(err) => { println!("server read error: {}", err); break; } } } if txn.read_closes { socket.set_read_timeout(Some(Duration::from_secs(1))).unwrap(); match socket.read(&mut [0; 256]) { Ok(0) => { continue 'txns }, Ok(_) => { panic!("server read expected EOF, found more bytes"); }, Err(err) => { panic!("server read expected EOF, got error: {}", err); } } } match (::std::str::from_utf8(&expected), ::std::str::from_utf8(&buf[..n])) { (Ok(expected), Ok(received)) => { if expected.len() > 300 && ::std::env::var("REQWEST_TEST_BODY_FULL").is_err() { assert_eq!( expected.len(), received.len(), "expected len = {}, received len = {}; to skip length check and see exact contents, re-run with REQWEST_TEST_BODY_FULL=1", expected.len(), received.len(), ); } assert_eq!(expected, received) }, _ => { assert_eq!( expected.len(), n, "expected len = {}, received len = {}", expected.len(), n, ); assert_eq!(expected, &buf[..n]) }, } if let Some(dur) = txn.response_timeout { thread::park_timeout(dur); } if let Some(dur) = txn.write_timeout { let headers_end = b"\r\n\r\n"; let headers_end = reply.windows(headers_end.len()).position(|w| w == headers_end).unwrap() + 4; socket.write_all(&reply[..headers_end]).unwrap(); let body = &reply[headers_end..]; if let Some(chunk_size) = txn.chunk_size { for content in body.chunks(chunk_size) { thread::park_timeout(dur); socket.write_all(&content).unwrap(); } } else { thread::park_timeout(dur); socket.write_all(&body).unwrap(); } } else { socket.write_all(&reply).unwrap(); } } let _ = panic_tx.send(()); }).expect("server thread spawn"); Server { addr, panic_rx, } } fn replace_expected_vars(bytes: &mut Vec<u8>, host: &[u8], ua: &[u8]) { let mut index = 0; loop { if index == bytes.len() { return; } for b in (&bytes[index..]).iter() { index += 1; if *b == b'$' { break; } } let has_host = (&bytes[index..]).starts_with(b"HOST"); if has_host { bytes.drain(index - 1..index + 4); for (i, b) in host.iter().enumerate() { bytes.insert(index - 1 + i, *b); } } else { let has_ua = (&bytes[index..]).starts_with(b"USERAGENT"); if has_ua { bytes.drain(index - 1..index + 9); for (i, b) in ua.iter().enumerate() { bytes.insert(index - 1 + i, *b); } } } } } #[macro_export] macro_rules! server { ($($($f:ident: $v:expr),+);*) => ({ let txns = vec![ $(__internal__txn! { $($f: $v,)+ }),* ]; ::support::server::spawn(txns) }) } #[macro_export] macro_rules! __internal__txn { ($($field:ident: $val:expr,)+) => ( ::support::server::Txn { $( $field: __internal__prop!($field: $val), )+ .. Default::default() } ) } #[macro_export] macro_rules! __internal__prop { (request: $val:expr) => ( From::from(&$val[..]) ); (response: $val:expr) => ( From::from(&$val[..]) ); ($field:ident: $val:expr) => ( From::from($val) ) }
use std::io::{Read, Write}; use std::net; use std::time::Duration; use std::sync::mpsc; use std::thread; pub struct Server { addr: net::SocketAddr, panic_rx: mpsc::Receiver<()>, } impl Server { pub fn addr(&self) -> net::SocketAddr { self.addr } } impl Drop for Server { fn drop(&mut self) { if !::std::thread::panicking() { self .
} #[derive(Debug, Default)] pub struct Txn { pub request: Vec<u8>, pub response: Vec<u8>, pub read_timeout: Option<Duration>, pub read_closes: bool, pub response_timeout: Option<Duration>, pub write_timeout: Option<Duration>, pub chunk_size: Option<usize>, } static DEFAULT_USER_AGENT: &'static str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")); pub fn spawn(txns: Vec<Txn>) -> Server { let listener = net::TcpListener::bind("127.0.0.1:0").unwrap(); let addr = listener.local_addr().unwrap(); let (panic_tx, panic_rx) = mpsc::channel(); let tname = format!("test({})-support-server", thread::current().name().unwrap_or("<unknown>")); thread::Builder::new().name(tname).spawn(move || { 'txns: for txn in txns { let mut expected = txn.request; let reply = txn.response; let (mut socket, _addr) = listener.accept().unwrap(); socket.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); replace_expected_vars(&mut expected, addr.to_string().as_ref(), DEFAULT_USER_AGENT.as_ref()); if let Some(dur) = txn.read_timeout { thread::park_timeout(dur); } let mut buf = vec![0; expected.len() + 256]; let mut n = 0; while n < expected.len() { match socket.read(&mut buf[n..]) { Ok(0) => { if !txn.read_closes { panic!("server unexpected socket closed"); } else { continue 'txns; } }, Ok(nread) => n += nread, Err(err) => { println!("server read error: {}", err); break; } } } if txn.read_closes { socket.set_read_timeout(Some(Duration::from_secs(1))).unwrap(); match socket.read(&mut [0; 256]) { Ok(0) => { continue 'txns }, Ok(_) => { panic!("server read expected EOF, found more bytes"); }, Err(err) => { panic!("server read expected EOF, got error: {}", err); } } } match (::std::str::from_utf8(&expected), ::std::str::from_utf8(&buf[..n])) { (Ok(expected), Ok(received)) => { if expected.len() > 300 && ::std::env::var("REQWEST_TEST_BODY_FULL").is_err() { assert_eq!( expected.len(), received.len(), "expected len = {}, received len = {}; to skip length check and see exact contents, re-run with REQWEST_TEST_BODY_FULL=1", expected.len(), received.len(), ); } assert_eq!(expected, received) }, _ => { assert_eq!( expected.len(), n, "expected len = {}, received len = {}", expected.len(), n, ); assert_eq!(expected, &buf[..n]) }, } if let Some(dur) = txn.response_timeout { thread::park_timeout(dur); } if let Some(dur) = txn.write_timeout { let headers_end = b"\r\n\r\n"; let headers_end = reply.windows(headers_end.len()).position(|w| w == headers_end).unwrap() + 4; socket.write_all(&reply[..headers_end]).unwrap(); let body = &reply[headers_end..]; if let Some(chunk_size) = txn.chunk_size { for content in body.chunks(chunk_size) { thread::park_timeout(dur); socket.write_all(&content).unwrap(); } } else { thread::park_timeout(dur); socket.write_all(&body).unwrap(); } } else { socket.write_all(&reply).unwrap(); } } let _ = panic_tx.send(()); }).expect("server thread spawn"); Server { addr, panic_rx, } } fn replace_expected_vars(bytes: &mut Vec<u8>, host: &[u8], ua: &[u8]) { let mut index = 0; loop { if index == bytes.len() { return; } for b in (&bytes[index..]).iter() { index += 1; if *b == b'$' { break; } } let has_host = (&bytes[index..]).starts_with(b"HOST"); if has_host { bytes.drain(index - 1..index + 4); for (i, b) in host.iter().enumerate() { bytes.insert(index - 1 + i, *b); } } else { let has_ua = (&bytes[index..]).starts_with(b"USERAGENT"); if has_ua { bytes.drain(index - 1..index + 9); for (i, b) in ua.iter().enumerate() { bytes.insert(index - 1 + i, *b); } } } } } #[macro_export] macro_rules! server { ($($($f:ident: $v:expr),+);*) => ({ let txns = vec![ $(__internal__txn! { $($f: $v,)+ }),* ]; ::support::server::spawn(txns) }) } #[macro_export] macro_rules! __internal__txn { ($($field:ident: $val:expr,)+) => ( ::support::server::Txn { $( $field: __internal__prop!($field: $val), )+ .. Default::default() } ) } #[macro_export] macro_rules! __internal__prop { (request: $val:expr) => ( From::from(&$val[..]) ); (response: $val:expr) => ( From::from(&$val[..]) ); ($field:ident: $val:expr) => ( From::from($val) ) }
panic_rx .recv_timeout(Duration::from_secs(3)) .expect("test server should not panic"); } }
function_block-function_prefix_line
[ { "content": "/// A future attempt to poll the response body for EOF so we know whether to use gzip or not.\n\nstruct Pending {\n\n body: ReadableChunks<Body>,\n\n}\n\n\n", "file_path": "src/async_impl/decoder.rs", "rank": 1, "score": 90916.19238636999 }, { "content": "/// A gzip decoder ...
Rust
components/dada-ir/src/code/syntax.rs
lqd/dada
df7d88dd006818699118a8bc4d3ecd2f108f438f
use crate::{ code::syntax::op::Op, in_ir_db::InIrDb, in_ir_db::InIrDbExt, span::Span, storage_mode::Atomic, word::{SpannedOptionalWord, Word}, }; use dada_id::{id, prelude::*, tables}; use salsa::DebugWithDb; use super::Code; salsa::entity2! { entity Tree in crate::Jar { origin: Code, #[value ref] data: TreeData, #[value ref] spans: Spans, } } impl DebugWithDb<dyn crate::Db> for Tree { fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &dyn crate::Db) -> std::fmt::Result { f.debug_struct("syntax::Tree") .field("origin", &self.origin(db).debug(db)) .field("data", &self.data(db).debug(&self.in_ir_db(db))) .finish() } } impl InIrDb<'_, Tree> { fn tables(&self) -> &Tables { &self.data(self.db()).tables } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct TreeData { pub tables: Tables, pub parameter_decls: Vec<LocalVariableDecl>, pub root_expr: Expr, } impl DebugWithDb<InIrDb<'_, Tree>> for TreeData { fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &InIrDb<'_, Tree>) -> std::fmt::Result { f.debug_struct("syntax::Tree") .field("root_expr", &self.root_expr.debug(db)) .finish() } } tables! { #[derive(Clone, Debug, PartialEq, Eq)] pub struct Tables { exprs: alloc Expr => ExprData, named_exprs: alloc NamedExpr => NamedExprData, local_variable_decls: alloc LocalVariableDecl => LocalVariableDeclData, } } origin_table! { #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] pub struct Spans { expr_spans: Expr => Span, named_expr_spans: NamedExpr => Span, local_variable_decl_spans: LocalVariableDecl => LocalVariableDeclSpan, } } id!(pub struct Expr); impl DebugWithDb<InIrDb<'_, Tree>> for Expr { fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &InIrDb<'_, Tree>) -> std::fmt::Result { f.debug_tuple("") .field(self) .field(&self.data(db.tables()).debug(db)) .finish() } } #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Hash, Debug)] pub enum ExprData { Id(Word), BooleanLiteral(bool), IntegerLiteral(Word, Option<Word>), FloatLiteral(Word, Word), StringLiteral(Word), Dot(Expr, Word), Await(Expr), Call(Expr, Vec<NamedExpr>), Share(Expr), Lease(Expr), Give(Expr), Var(LocalVariableDecl, Expr), Parenthesized(Expr), Tuple(Vec<Expr>), If(Expr, Expr, Option<Expr>), Atomic(Expr), Loop(Expr), While(Expr, Expr), Seq(Vec<Expr>), Op(Expr, Op, Expr), OpEq(Expr, Op, Expr), Unary(Op, Expr), Assign(Expr, Expr), Return(Option<Expr>), Error, } impl DebugWithDb<InIrDb<'_, Tree>> for ExprData { fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &InIrDb<'_, Tree>) -> std::fmt::Result { match self { ExprData::Id(w) => f.debug_tuple("Id").field(&w.debug(db.db())).finish(), ExprData::BooleanLiteral(v) => f.debug_tuple("Boolean").field(&v).finish(), ExprData::IntegerLiteral(v, _) => { f.debug_tuple("Integer").field(&v.debug(db.db())).finish() } ExprData::FloatLiteral(v, d) => f .debug_tuple("Float") .field(&v.debug(db.db())) .field(&d.debug(db.db())) .finish(), ExprData::StringLiteral(v) => f.debug_tuple("String").field(&v.debug(db.db())).finish(), ExprData::Dot(lhs, rhs) => f .debug_tuple("Dot") .field(&lhs.debug(db)) .field(&rhs.debug(db.db())) .finish(), ExprData::Await(e) => f.debug_tuple("Await").field(&e.debug(db)).finish(), ExprData::Call(func, args) => f .debug_tuple("Call") .field(&func.debug(db)) .field(&args.debug(db)) .finish(), ExprData::Share(e) => f.debug_tuple("Share").field(&e.debug(db)).finish(), ExprData::Lease(e) => f.debug_tuple("Lease").field(&e.debug(db)).finish(), ExprData::Give(e) => f.debug_tuple("Give").field(&e.debug(db)).finish(), ExprData::Var(v, e) => f .debug_tuple("Var") .field(&v.debug(db)) .field(&e.debug(db)) .finish(), ExprData::Parenthesized(e) => f.debug_tuple("Share").field(&e.debug(db)).finish(), ExprData::Tuple(e) => f.debug_tuple("Tuple").field(&e.debug(db)).finish(), ExprData::If(c, t, e) => f .debug_tuple("If") .field(&c.debug(db)) .field(&t.debug(db)) .field(&e.debug(db)) .finish(), ExprData::Atomic(e) => f.debug_tuple("Atomic").field(&e.debug(db)).finish(), ExprData::Loop(e) => f.debug_tuple("Loop").field(&e.debug(db)).finish(), ExprData::While(c, e) => f .debug_tuple("While") .field(&c.debug(db)) .field(&e.debug(db)) .finish(), ExprData::Seq(e) => f.debug_tuple("Seq").field(&e.debug(db)).finish(), ExprData::Op(l, o, r) => f .debug_tuple("Op") .field(&l.debug(db)) .field(&o) .field(&r.debug(db)) .finish(), ExprData::OpEq(l, o, r) => f .debug_tuple("OpEq") .field(&l.debug(db)) .field(&o) .field(&r.debug(db)) .finish(), ExprData::Assign(l, r) => f .debug_tuple("Assign") .field(&l.debug(db)) .field(&r.debug(db)) .finish(), ExprData::Error => f.debug_tuple("Error").finish(), ExprData::Return(e) => f.debug_tuple("Return").field(&e.debug(db)).finish(), ExprData::Unary(o, e) => f .debug_tuple("Unary") .field(&o) .field(&e.debug(db)) .finish(), } } } id!(pub struct LocalVariableDecl); impl DebugWithDb<InIrDb<'_, Tree>> for LocalVariableDecl { fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &InIrDb<'_, Tree>) -> std::fmt::Result { DebugWithDb::fmt(self.data(db.tables()), f, db) } } #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Hash, Debug)] pub struct LocalVariableDeclData { pub atomic: Atomic, pub name: Word, pub ty: Option<crate::ty::Ty>, } impl DebugWithDb<InIrDb<'_, Tree>> for LocalVariableDeclData { fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &InIrDb<'_, Tree>) -> std::fmt::Result { f.debug_tuple("") .field(&self.name.debug(db.db())) .field(&self.ty.debug(db.db())) .finish() } } #[derive(PartialEq, Eq, Clone, Hash, Debug)] pub struct LocalVariableDeclSpan { pub atomic_span: Span, pub name_span: Span, } id!(pub struct NamedExpr); impl DebugWithDb<InIrDb<'_, Tree>> for NamedExpr { fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &InIrDb<'_, Tree>) -> std::fmt::Result { DebugWithDb::fmt(self.data(db.tables()), f, db) } } #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Hash, Debug)] pub struct NamedExprData { pub name: SpannedOptionalWord, pub expr: Expr, } impl DebugWithDb<InIrDb<'_, Tree>> for NamedExprData { fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &InIrDb<'_, Tree>) -> std::fmt::Result { f.debug_tuple("") .field(&self.name.word(db.db()).debug(db.db())) .field(&self.expr.debug(db)) .finish() } } pub mod op;
use crate::{ code::syntax::op::Op, in_ir_db::InIrDb, in_ir_db::InIrDbExt, span::Span, storage_mode::Atomic, word::{SpannedOptionalWord, Word}, }; use dada_id::{id, prelude::*, tables}; use salsa::DebugWithDb; use super::Code; salsa::entity2! { entity Tree in crate::Jar { origin: Code, #[value ref] data: TreeData, #[value ref] spans: Spans, } } impl DebugWithDb<dyn crate::Db> for Tree { fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &dyn crate::Db) -> std::fmt::Result { f.debug_struct("syntax::Tree") .field("origin", &self.origin(db).debug(db)) .field("data", &self.data(db).debug(&self.in_ir_db(db))) .finish() } } impl InIrDb<'_, Tree> { fn tables(&self) -> &Tables { &self.data(self.db()).tables } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct TreeData { pub tables: Tables, pub parameter_decls: Vec<LocalVariableDecl>, pub root_expr: Expr, } impl DebugWithDb<InI
StringLiteral(Word), Dot(Expr, Word), Await(Expr), Call(Expr, Vec<NamedExpr>), Share(Expr), Lease(Expr), Give(Expr), Var(LocalVariableDecl, Expr), Parenthesized(Expr), Tuple(Vec<Expr>), If(Expr, Expr, Option<Expr>), Atomic(Expr), Loop(Expr), While(Expr, Expr), Seq(Vec<Expr>), Op(Expr, Op, Expr), OpEq(Expr, Op, Expr), Unary(Op, Expr), Assign(Expr, Expr), Return(Option<Expr>), Error, } impl DebugWithDb<InIrDb<'_, Tree>> for ExprData { fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &InIrDb<'_, Tree>) -> std::fmt::Result { match self { ExprData::Id(w) => f.debug_tuple("Id").field(&w.debug(db.db())).finish(), ExprData::BooleanLiteral(v) => f.debug_tuple("Boolean").field(&v).finish(), ExprData::IntegerLiteral(v, _) => { f.debug_tuple("Integer").field(&v.debug(db.db())).finish() } ExprData::FloatLiteral(v, d) => f .debug_tuple("Float") .field(&v.debug(db.db())) .field(&d.debug(db.db())) .finish(), ExprData::StringLiteral(v) => f.debug_tuple("String").field(&v.debug(db.db())).finish(), ExprData::Dot(lhs, rhs) => f .debug_tuple("Dot") .field(&lhs.debug(db)) .field(&rhs.debug(db.db())) .finish(), ExprData::Await(e) => f.debug_tuple("Await").field(&e.debug(db)).finish(), ExprData::Call(func, args) => f .debug_tuple("Call") .field(&func.debug(db)) .field(&args.debug(db)) .finish(), ExprData::Share(e) => f.debug_tuple("Share").field(&e.debug(db)).finish(), ExprData::Lease(e) => f.debug_tuple("Lease").field(&e.debug(db)).finish(), ExprData::Give(e) => f.debug_tuple("Give").field(&e.debug(db)).finish(), ExprData::Var(v, e) => f .debug_tuple("Var") .field(&v.debug(db)) .field(&e.debug(db)) .finish(), ExprData::Parenthesized(e) => f.debug_tuple("Share").field(&e.debug(db)).finish(), ExprData::Tuple(e) => f.debug_tuple("Tuple").field(&e.debug(db)).finish(), ExprData::If(c, t, e) => f .debug_tuple("If") .field(&c.debug(db)) .field(&t.debug(db)) .field(&e.debug(db)) .finish(), ExprData::Atomic(e) => f.debug_tuple("Atomic").field(&e.debug(db)).finish(), ExprData::Loop(e) => f.debug_tuple("Loop").field(&e.debug(db)).finish(), ExprData::While(c, e) => f .debug_tuple("While") .field(&c.debug(db)) .field(&e.debug(db)) .finish(), ExprData::Seq(e) => f.debug_tuple("Seq").field(&e.debug(db)).finish(), ExprData::Op(l, o, r) => f .debug_tuple("Op") .field(&l.debug(db)) .field(&o) .field(&r.debug(db)) .finish(), ExprData::OpEq(l, o, r) => f .debug_tuple("OpEq") .field(&l.debug(db)) .field(&o) .field(&r.debug(db)) .finish(), ExprData::Assign(l, r) => f .debug_tuple("Assign") .field(&l.debug(db)) .field(&r.debug(db)) .finish(), ExprData::Error => f.debug_tuple("Error").finish(), ExprData::Return(e) => f.debug_tuple("Return").field(&e.debug(db)).finish(), ExprData::Unary(o, e) => f .debug_tuple("Unary") .field(&o) .field(&e.debug(db)) .finish(), } } } id!(pub struct LocalVariableDecl); impl DebugWithDb<InIrDb<'_, Tree>> for LocalVariableDecl { fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &InIrDb<'_, Tree>) -> std::fmt::Result { DebugWithDb::fmt(self.data(db.tables()), f, db) } } #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Hash, Debug)] pub struct LocalVariableDeclData { pub atomic: Atomic, pub name: Word, pub ty: Option<crate::ty::Ty>, } impl DebugWithDb<InIrDb<'_, Tree>> for LocalVariableDeclData { fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &InIrDb<'_, Tree>) -> std::fmt::Result { f.debug_tuple("") .field(&self.name.debug(db.db())) .field(&self.ty.debug(db.db())) .finish() } } #[derive(PartialEq, Eq, Clone, Hash, Debug)] pub struct LocalVariableDeclSpan { pub atomic_span: Span, pub name_span: Span, } id!(pub struct NamedExpr); impl DebugWithDb<InIrDb<'_, Tree>> for NamedExpr { fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &InIrDb<'_, Tree>) -> std::fmt::Result { DebugWithDb::fmt(self.data(db.tables()), f, db) } } #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Hash, Debug)] pub struct NamedExprData { pub name: SpannedOptionalWord, pub expr: Expr, } impl DebugWithDb<InIrDb<'_, Tree>> for NamedExprData { fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &InIrDb<'_, Tree>) -> std::fmt::Result { f.debug_tuple("") .field(&self.name.word(db.db()).debug(db.db())) .field(&self.expr.debug(db)) .finish() } } pub mod op;
rDb<'_, Tree>> for TreeData { fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &InIrDb<'_, Tree>) -> std::fmt::Result { f.debug_struct("syntax::Tree") .field("root_expr", &self.root_expr.debug(db)) .finish() } } tables! { #[derive(Clone, Debug, PartialEq, Eq)] pub struct Tables { exprs: alloc Expr => ExprData, named_exprs: alloc NamedExpr => NamedExprData, local_variable_decls: alloc LocalVariableDecl => LocalVariableDeclData, } } origin_table! { #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] pub struct Spans { expr_spans: Expr => Span, named_expr_spans: NamedExpr => Span, local_variable_decl_spans: LocalVariableDecl => LocalVariableDeclSpan, } } id!(pub struct Expr); impl DebugWithDb<InIrDb<'_, Tree>> for Expr { fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &InIrDb<'_, Tree>) -> std::fmt::Result { f.debug_tuple("") .field(self) .field(&self.data(db.tables()).debug(db)) .finish() } } #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Hash, Debug)] pub enum ExprData { Id(Word), BooleanLiteral(bool), IntegerLiteral(Word, Option<Word>), FloatLiteral(Word, Word),
random
[ { "content": "#[salsa::memoized(in crate::Jar)]\n\npub fn parse_code(db: &dyn crate::Db, code: Code) -> Tree {\n\n let body = code.body_tokens;\n\n Parser::new(db, body).parse_code_body(code)\n\n}\n", "file_path": "components/dada-parse/src/code_parser.rs", "rank": 0, "score": 385982.550388712...
Rust
tools/cli/src/utils.rs
brygga-dev/workdir2
0b6e8f54a3d44ef8dedefd1bdc95f193467d239e
use console::style; use dialoguer::{theme, Input, Select}; use std::fs; use std::io; use std::path::{Path, PathBuf}; use shared_child::SharedChild; use std::sync::Arc; use std::sync::RwLock; use std::net::TcpStream; use std::net::ToSocketAddrs; pub struct ConfigDir(pub PathBuf); impl ConfigDir { pub fn new(config_root: &PathBuf, folder: &str) -> ConfigDir { let mut config_dir = config_root.clone(); config_dir.push(folder); ConfigDir(config_dir) } pub fn filepath(&self, file: &str) -> PathBuf { let mut filepath = self.0.clone(); filepath.push(file); filepath } pub fn has_file(&self, file: &str) -> bool { let mut test = self.0.clone(); test.push(file); test.is_file() } pub fn write(&self, file: &str, content: &str) -> io::Result<()> { write_file(&self.filepath(file), content) } } pub struct ConfigDirs { pub git_accounts: ConfigDir, pub projects: ConfigDir, pub servers: ConfigDir, pub config_root: PathBuf, } impl ConfigDirs { pub fn new(projects_dir: PathBuf) -> ConfigDirs { let mut config_root = projects_dir.clone(); config_root.push(".config"); ConfigDirs { git_accounts: ConfigDir::new(&config_root, "git_accounts"), projects: ConfigDir::new(&config_root, "projects"), servers: ConfigDir::new(&config_root, "servers"), config_root, } } } pub struct CliEnv { pub projects_dir: PathBuf, pub workdir_dir: PathBuf, pub config_dirs: ConfigDirs, theme: theme::ColorfulTheme, } pub enum SelectOrAdd { Selected(usize), AddNew, } impl CliEnv { pub fn new(projects_dir: PathBuf, workdir_dir: PathBuf) -> CliEnv { CliEnv { projects_dir: projects_dir.clone(), workdir_dir: workdir_dir, config_dirs: ConfigDirs::new(projects_dir), theme: theme::ColorfulTheme::default(), } } pub fn get_input(&self, prompt: &str, default: Option<String>) -> io::Result<String> { let term = console::Term::stderr(); let mut input_build = Input::<String>::with_theme(&self.theme); input_build.with_prompt(&prompt); default.iter().for_each(|default| { input_build.default(default.to_owned()); }); let input = input_build.interact_on(&term)?; let input = input.trim(); let resolved = if input != "" { String::from(input) } else { match default { Some(default) => default.into(), _ => String::from(input), } }; term.clear_last_lines(1)?; term.write_line(&format!("{}: {}", prompt, style(&resolved).magenta()))?; Ok(resolved) } pub fn get_pass(&self, prompt: &str) -> io::Result<String> { let mut input_build = dialoguer::PasswordInput::with_theme(&self.theme); input_build.with_prompt(&prompt); input_build.interact() } pub fn select<T: ToString + std::cmp::PartialEq + Clone>( &self, prompt: &str, items: &Vec<T>, default: Option<usize>, ) -> io::Result<usize> { let prompt = match default { Some(default) => match items.get(default) { Some(default_val) => { format!("{} ({})", prompt, style(default_val.to_string()).dim()) } None => prompt.to_string(), }, None => String::from(prompt), }; let mut select_build = Select::with_theme(&self.theme); select_build.with_prompt(&prompt).items(items); select_build.default(default.unwrap_or(0)); let index = select_build.interact()?; Ok(index) } pub fn select_or_add<T: ToString + std::cmp::PartialEq + Clone>( &self, prompt: &str, items: &Vec<T>, default: Option<usize>, ) -> io::Result<SelectOrAdd> { let num_regular = items.len(); let mut items2 = items.iter().map(|i| i.to_string()).collect::<Vec<String>>(); items2.push("ADD NEW".to_string()); let select_res = self.select(prompt, &items2, default)?; if select_res < num_regular { Ok(SelectOrAdd::Selected(select_res)) } else { Ok(SelectOrAdd::AddNew) } } pub fn error_msg(&self, msg: &str) { println!("{}", style(msg).red()); } pub fn get_project_path(&self, extra: &str) -> PathBuf { let mut cloned = self.projects_dir.clone(); cloned.push(extra); cloned } pub fn display_result<T>(&self, result: io::Result<T>) { match result { Ok(_) => (), Err(err) => self.error_msg(&format!("{:?}", err)), } } } pub fn entries_in_dir(dir: &Path) -> io::Result<Vec<PathBuf>> { let mut entries = Vec::new(); if !dir.is_dir() { return Err(io::Error::from(io::ErrorKind::InvalidInput)); } for entry in fs::read_dir(dir)? { let entry = entry?; let path = entry.path(); if path.is_dir() || path.is_file() { entries.push(path); } } Ok(entries) } pub fn files_in_dir(dir: &Path) -> io::Result<Vec<String>> { if dir.is_dir() { let mut entries = Vec::new(); for entry in std::fs::read_dir(dir)? { let entry = entry?; match entry.file_name().into_string() { Ok(string) => entries.push(string), Err(_) => (), } } Ok(entries) } else { Ok(Vec::new()) } } pub fn name_after_prefix(full_path: &Path, prefix: &Path) -> io::Result<String> { match full_path.strip_prefix(&prefix) { Ok(stripped) => { match stripped.file_name() { Some(name) => Ok(name.to_string_lossy().to_string()), None => io_err(format!("Could not get name from: {:?}", stripped)), } } Err(e) => io_err(format!("Error strip prefix: {:?}", e)), } } pub fn file_name_string(path: &Path) -> io::Result<String> { match path.file_name() { Some(file_name) => Ok(file_name.to_string_lossy().to_string()), None => io_err(format!("Could not get file_name from {:?}", path)), } } pub fn ensure_parent_dir(path: &Path) -> io::Result<()> { match path.parent() { Some(parent) => { if parent.is_dir() { Ok(()) } else { fs::create_dir_all(parent) } } None => io_err(format!("Could not resolve parent of {:?}", path)), } } pub fn write_file(path: &Path, content: &str) -> io::Result<()> { ensure_parent_dir(path)?; fs::write(path, content) } pub fn io_error<M: Into<String>>(msg: M) -> io::Error { io::Error::new(io::ErrorKind::Other, msg.into()) } pub fn io_err<T, M: Into<String>>(msg: M) -> io::Result<T> { Err(io::Error::new(io::ErrorKind::Other, msg.into())) } pub struct CurrentProcess(Arc<RwLock<Option<(SharedChild, bool)>>>); impl CurrentProcess { pub fn new() -> CurrentProcess { let current_process: Arc<RwLock<Option<(SharedChild, bool)>>> = Arc::new(RwLock::new(None)); let current_process_ctrlc = current_process.clone(); match ctrlc::set_handler(move || { let current_process = match current_process_ctrlc.read() { Ok(lock) => lock, Err(e) => { println!("Error aquiring lock: {:?}", e); return (); } }; match &*current_process { Some((process, end_on_ctrlc)) => { if *end_on_ctrlc { match process.kill() { Ok(_) => { println!("Ended process by ctrl-c"); () } Err(e) => println!("Error ending dev process: {:?}", e), } } } None => { println!("No current process in ctrlc"); std::process::exit(0); } } }) { Ok(_) => (), Err(e) => println!("Ctrlc error: {:?}", e), } CurrentProcess(current_process) } pub fn spawn_and_wait( self, mut cmd: std::process::Command, end_on_ctrlc: bool, ) -> io::Result<Self> { { let shared_child = shared_child::SharedChild::spawn(&mut cmd)?; match self.0.write() { Ok(mut write_lock) => *write_lock = Some((shared_child, end_on_ctrlc)), Err(e) => { println!("Couldn't aqcuire write lock: {:?}", e); } } } let wait_clone = self.0.clone(); let thread = std::thread::spawn(move || { { let reader = match wait_clone.read() { Ok(reader) => reader, Err(e) => { print!("Could not get read lock: {:?}", e); return (); } }; let wait_process = match &*reader { Some((wait_process, _)) => wait_process, None => return (), }; match wait_process.wait() { Ok(exit_status) => { println!("Exited dev process with status: {}", exit_status); } Err(e) => { println!("Error waiting for process: {:?}", e); return (); } } } match wait_clone.write() { Ok(mut lock) => { *lock = None; } Err(e) => println!("Failed getting write on current process: {:?}", e), } }); let _thread_res = match thread.join() { Ok(_res) => { println!("Joined thread"); } Err(e) => println!("Error ending process: {:?}", e), }; Ok(self) } } pub fn wait_for<A: ToSocketAddrs>(addr: A) -> bool { let mut attempts = 0; let max_attempts = 15; loop { match TcpStream::connect(&addr) { Ok(_) => { if attempts > 0 { std::thread::sleep(std::time::Duration::from_millis(2000)); } return true; } Err(e) => { println!("Could not connect, retrying..."); attempts = attempts + 1; if attempts >= max_attempts { format!("Aborting after max attempts: {}, {:?}", max_attempts, e); return false; } std::thread::sleep(std::time::Duration::from_millis(1500)); } } } } pub fn now_formatted() -> String { let system_time = std::time::SystemTime::now(); let datetime: chrono::DateTime<chrono::Utc> = system_time.into(); format!("{}", datetime.format("%Y-%m-%d %T")) }
use console::style; use dialoguer::{theme, Input, Select}; use std::fs; use std::io; use std::path::{Path, PathBuf}; use shared_child::SharedChild; use std::sync::Arc; use std::sync::RwLock; use std::net::TcpStream; use std::net::ToSocketAddrs; pub struct ConfigDir(pub PathBuf); impl ConfigDir { pub fn new(config_root: &PathBuf, folder: &str) -> ConfigDir { let mut config_dir = config_root.clone(); config_dir.push(folder); ConfigDir(config_dir) } pub fn filepath(&self, file: &str) -> PathBuf { let mut filepath = self.0.clone(); filepath.push(file); filepath } pub fn has_file(&self, file: &str) -> bool { let mut test = self.0.clone(); test.push(file); test.is_file() } pub fn write(&self, file: &str, content: &str) -> io::Result<()> { write_file(&self.filepath(file), content) } } pub struct ConfigDirs { pub git_accounts: ConfigDir, pub projects: ConfigDir, pub servers: ConfigDir, pub config_root: PathBuf, } impl ConfigDirs { pub fn new(projects_dir: PathBuf) -> ConfigDirs { let mut config_root = projects_dir.clone(); config_root.push(".config"); ConfigDirs { git_accounts: ConfigDir::new(&config_root, "git_accounts"), projects: ConfigDir::new(&config_root, "projects"), servers: ConfigDir::new(&config_root, "servers"), config_root, } } } pub struct CliEnv { pub projects_dir: PathBuf, pub workdir_dir: PathBuf, pub config_dirs: ConfigDirs, theme: theme::ColorfulTheme, } pub enum SelectOrAdd { Selected(usize), AddNew, } impl CliEnv { pub fn new(projects_dir: PathBuf, workdir_dir: PathBuf) -> CliEnv { CliEnv { projects_dir: projects_dir.clone(), workdir_dir: workdir_dir, config_dirs: ConfigDirs::new(projects_dir), theme: theme::ColorfulTheme::default(), } } pub fn get_input(&self, prompt: &str, default: Option<String>) -> io::Result<String> { let term = console::Term::stderr(); let mut input_build = Input::<String>::with_theme(&self.theme); input_build.with_prompt(&prompt); default.iter().for_each(|default| { input_build.default(default.to_owned()); }); let input = input_build.interact_on(&term)?; let input = input.trim(); let resolved = if input != "" { String::from(input) } else { match default { Some(default) => default.into(), _ => String::from(input), } }; term.clear_last_lines(1)?; term.write_line(&format!("{}: {}", prompt, style(&resolved).magenta()))?; Ok(resolved) } pub fn get_pass(&self, prompt: &str) -> io::Result<String> { let mut input_build = dialoguer::PasswordInput::with_theme(&self.theme); input_build.with_prompt(&prompt); input_build.interact() } pub fn select<T: ToString + std::cmp::PartialEq + Clone>( &self, prompt: &str, items: &Vec<T>, default: Option<usize>, ) -> io::Result<usize> { let prompt = match default { Some(default) => match items.get(default) { Some(default_val) => { format!("{} ({})", prompt, style(default_val.to_string()).dim()) } None => prompt.to_string(), }, None => String::from(prompt), }; let mut select_build = Select::with_theme(&self.theme); select_build.with_prompt(&prompt).items(items); select_build.default(default.unwrap_or(0)); let index = select_build.interact()?; Ok(index) } pub fn select_or_add<T: ToString + std::cmp::PartialEq + Clone>( &self, prompt: &str, items: &Vec<T>, default: Option<usize>, ) -> io::Result<SelectOrAdd> { let num_regular = items.len(); let mut items2 = items.iter().map(|i| i.to_string()).collect::<Vec<String>>(); items2.push("ADD NEW".to_string()); let select_res = self.select(prompt, &items2, default)?; if select_res < num_regular { Ok(SelectOrAdd::Selected(select_res)) } else { Ok(SelectOrAdd::AddNew) } } pub fn error_msg(&self, msg: &str) { println!("{}", style(msg).red()); } pub fn get_project_path(&self, extra: &str) -> PathBuf { let mut cloned = self.projects_dir.clone(); cloned.push(extra); cloned } pub fn display_result<T>(&self, result: io::Result<T>) { match result { Ok(_) => (), Err(err) => self.error_msg(&format!("{:?}", err)), } } } pub fn entries_in_dir(dir: &Path) -> io::Result<Vec<PathBuf>> { let mut entries = Vec::new(); if !dir.is_dir() { return Err(io::Error::from(io::ErrorKind::InvalidInput)); } for entry in fs::read_dir(dir)? { let entry = entry?; let path = entry.path(); if path.is_dir() || path.is_file() { entries.push(path); } } Ok(entries) } pub fn files_in_dir(dir: &Path) -> io::Result<Vec<String>> { if dir.is_dir() { let mut entries = Vec::new(); for entry in std::fs::read_dir(dir)? { let entry = entry?; match entry.file_name().into_string() { Ok(string) => entries.push(string), Err(_) => (), } } Ok(entries) } else { Ok(Vec::new()) } } pub fn name_after_prefix(full_path: &Path, prefix: &Path) -> io::Result<String> { match full_path.strip_prefix(&prefix) { Ok(stripped) => { match stripped.file_name() { Some(name) => Ok(name.to_string_lossy().to_string()), None => io_err(format!("Could not get name from: {:?}", stripped)), } } Err(e) => io_err(format!("Error strip prefix: {:?}", e)), } } pub fn file_name_string(path: &Path) -> io::Result<String> { match path.file_name() { Some(file_name) => Ok(file_name.to_string_lossy().to_string()), None => io_err(format!("Could not get file_name from {:?}", path)), } } pub fn ensure_parent_dir(path: &Path) -> io::Result<()> { match path.parent() { Some(parent) => { if parent.is_dir() { Ok(()) } else { fs::create_dir_all(parent) } } None => io_err(format!("Could not resolve parent of {:?}", path)), } } pub fn write_file(path: &Path, content: &str) -> io::Result<()> { ensure_parent_dir(path)?; fs::write(path, content) } pub fn io_error<M: Into<String>>(msg: M) -> io::Error { io::Error::new(io::ErrorKind::Other, msg.into()) } pub fn io_err<T, M: Into<String>>(msg: M) -> io::Result<T> { Err(io::Error::new(io::ErrorKind::Other, msg.into())) } pub struct CurrentProcess(Arc<RwLock<Option<(SharedChild, bool)>>>); impl CurrentProcess { pub fn new() -> CurrentProcess { let current_process: Arc<RwLock<Option<(SharedChild, bool)>>> = Arc::new(RwLock::new(None)); let current_process_ctrlc = current_process.clone(); match ctrlc::set_handler(move || { let current_process = match current_process_ctrlc.read() { Ok(lock) => lock, Err(e) => { println!("Error aquiring lock: {:?}", e); return (); } }; match &*current_process { Some((process, end_on_ctrlc)) => { if *end_on_ctrlc { match process.kill() { Ok(_) => { println!("Ended process by ctrl-c"); () } Err(e) => println!("Error ending dev process: {:?}", e), } } } None => { println!("No current process in ctrlc"); std::process::exit(0); } } }) { Ok(_) => (), Err(e) => println!("Ctrlc error: {:?}", e), } CurrentProcess(current_process) } pub fn spawn_and_wait( self, mut cmd: std::process::Command, end_on_ctrlc: bool, ) -> io::Result<Self> { { let shared_child = shared_child::SharedChild::spawn(&mut cmd)?; match self.0.write() { Ok(mut write_lock) => *write_lock = Some((shared_child, end_on_ctrlc)), Err(e) => { println!("Couldn't aqcuire write lock: {:?}", e); } } } let wait_clone = self.0.clone(); let thread = std::thread::spawn(move || { { let reader = match wait_clone.read() { Ok(reader) => reader, Err(e) => { print!("Could not get read lock: {:?}", e); return (); } }; let wait_process = match &*reader { Some((wait_process, _)) => wait_process, None => return (), }; match wait_process.wait() { Ok(exit_status) => { println!("Exited dev process with status: {}", exit_status); } Err(e) => { println!("Error waiting for process: {:?}", e); return (); } } }
}); let _thread_res = match thread.join() { Ok(_res) => { println!("Joined thread"); } Err(e) => println!("Error ending process: {:?}", e), }; Ok(self) } } pub fn wait_for<A: ToSocketAddrs>(addr: A) -> bool { let mut attempts = 0; let max_attempts = 15; loop { match TcpStream::connect(&addr) { Ok(_) => { if attempts > 0 { std::thread::sleep(std::time::Duration::from_millis(2000)); } return true; } Err(e) => { println!("Could not connect, retrying..."); attempts = attempts + 1; if attempts >= max_attempts { format!("Aborting after max attempts: {}, {:?}", max_attempts, e); return false; } std::thread::sleep(std::time::Duration::from_millis(1500)); } } } } pub fn now_formatted() -> String { let system_time = std::time::SystemTime::now(); let datetime: chrono::DateTime<chrono::Utc> = system_time.into(); format!("{}", datetime.format("%Y-%m-%d %T")) }
match wait_clone.write() { Ok(mut lock) => { *lock = None; } Err(e) => println!("Failed getting write on current process: {:?}", e), }
if_condition
[ { "content": "// Not ideally, but split initially with init_project_config\n\n// to avoid type complexity with future and io:Result\n\npub fn init_cmd<'a>(env: &'a CliEnv) -> impl Future<Item = (), Error = Error> + 'a {\n\n let (config, project_git) = match init_project_config(env) {\n\n Ok(config) =>...
Rust
src/html.rs
Traverse-Research/markdown.rs
cca09f697f58d4ce68649e1873ff76983f2d6a37
use parser::Block; use parser::Block::{ Blockquote, CodeBlock, Header, Hr, LinkReference, OrderedList, Paragraph, Raw, UnorderedList, }; use parser::Span::{Break, Code, Emphasis, Image, Link, Literal, RefLink, Strong, Text}; use parser::{ListItem, OrderedListType, Span}; use regex::Regex; use std::collections::HashMap; type LinkReferenceMap<'a> = HashMap<&'a str, (&'a str, &'a Option<String>)>; fn slugify(elements: &[Span], no_spaces: bool) -> String { let mut ret = String::new(); for el in elements { let next = match *el { Break => "".to_owned(), Literal(character) => character.to_string(), Text(ref text) | Image(ref text, _, _) | Code(ref text) => text.trim().to_lowercase(), RefLink(ref content, _, _) | Link(ref content, _, _) | Strong(ref content) | Emphasis(ref content) => slugify(content, no_spaces), }; if !ret.is_empty() { ret.push('_'); } ret.push_str(&next); } if no_spaces { ret = ret.replace(" ", "_"); } ret } pub fn to_html(blocks: &[Block]) -> String { let mut ret = String::new(); let mut link_references: LinkReferenceMap = HashMap::new(); for block in blocks.iter() { match block { LinkReference(ref id, ref text, ref title) => { link_references.insert(id, (text, title)); } _ => {} }; } for block in blocks.iter() { let next = match block { Header(ref elements, level) => format_header(elements, *level, &link_references), Paragraph(ref elements) => format_paragraph(elements, &link_references), Blockquote(ref elements) => format_blockquote(elements), CodeBlock(ref lang, ref elements) => format_codeblock(lang, elements), UnorderedList(ref elements) => format_unordered_list(elements, &link_references), OrderedList(ref elements, ref num_type) => { format_ordered_list(elements, num_type, &link_references) } LinkReference(_, _, _) => "".to_owned(), Raw(ref elements) => elements.to_owned(), Hr => format!("<hr />\n\n"), }; ret.push_str(&next) } ret = ret.trim().to_owned(); ret.push('\n'); ret } fn format_spans(elements: &[Span], link_references: &LinkReferenceMap) -> String { let mut ret = String::new(); for element in elements.iter() { let next = match *element { Break => format!("<br />"), Literal(character) => character.to_string(), Text(ref text) => format!("{}", &escape(text, true)), Code(ref text) => format!("<code>{}</code>", &escape(text, false)), Link(ref content, ref url, None) => format!( "<a href=\"{}\">{}</a>", &escape(url, false), format_spans(content, link_references) ), Link(ref content, ref url, Some(ref title)) => format!( "<a href=\"{}\" title=\"{}\">{}</a>", &escape(url, false), &escape(title, true), format_spans(content, link_references) ), RefLink(ref content, ref reference, ref raw) => { if let Some((ref url, None)) = link_references.get::<str>(reference) { format!( "<a href=\"{}\">{}</a>", &escape(url, false), format_spans(content, link_references) ) } else if let Some((ref url, Some(ref title))) = link_references.get::<str>(reference) { format!( "<a href=\"{}\" title=\"{}\">{}</a>", &escape(url, false), &escape(title, true), format_spans(content, link_references) ) } else if let Some((ref url, None)) = link_references.get::<str>(&slugify(content, false)) { format!( "<a href=\"{}\">{}</a>", &escape(url, false), format_spans(content, link_references) ) } else if let Some((ref url, Some(ref title))) = link_references.get::<str>(&slugify(content, false)) { format!( "<a href=\"{}\" title=\"{}\">{}</a>", &escape(url, false), &escape(title, true), format_spans(content, link_references) ) } else { raw.to_owned() } } Image(ref text, ref url, None) => format!( "<img src=\"{}\" alt=\"{}\" />", &escape(url, false), &escape(text, true) ), Image(ref text, ref url, Some(ref title)) => format!( "<img src=\"{}\" title=\"{}\" alt=\"{}\" />", &escape(url, false), &escape(title, true), &escape(text, true) ), Emphasis(ref content) => format!("<em>{}</em>", format_spans(content, link_references)), Strong(ref content) => format!( "<strong>{}</strong>", format_spans(content, link_references) ), }; ret.push_str(&next) } ret } fn escape(text: &str, replace_entities: bool) -> String { lazy_static! { static ref AMPERSAND: Regex = Regex::new(r"&amp;(?P<x>\S+;)").unwrap(); } let replaced = text .replace("&", "&amp;") .replace("<", "&lt;") .replace("\"", "&quot;") .replace("'", "&#8217;") .replace(">", "&gt;"); if replace_entities { return AMPERSAND.replace_all(&replaced, "&$x").into_owned(); } return replaced; } fn format_list( elements: &[ListItem], start_tag: &str, end_tag: &str, link_references: &LinkReferenceMap, ) -> String { let mut ret = String::new(); for list_item in elements { let mut content = String::new(); match *list_item { ListItem::Simple(ref els) => content.push_str(&format_spans(els, link_references)), ListItem::Paragraph(ref paragraphs) => { content.push_str(&format!("\n{}", to_html(paragraphs))) } } ret.push_str(&format!("\n<li>{}</li>\n", content)) } format!("<{}>{}</{}>\n\n", start_tag, ret, end_tag) } fn format_unordered_list(elements: &[ListItem], link_references: &LinkReferenceMap) -> String { format_list(elements, "ul", "ul", link_references) } fn format_ordered_list( elements: &[ListItem], num_type: &OrderedListType, link_references: &LinkReferenceMap, ) -> String { if num_type != &OrderedListType::Numeric { format_list( elements, &format!("ol type=\"{}\"", num_type.to_str()), "ol", link_references, ) } else { format_list(elements, "ol", "ol", link_references) } } fn format_codeblock(lang: &Option<String>, elements: &str) -> String { if lang.is_none() || (lang.is_some() && lang.as_ref().unwrap().is_empty()) { format!("<pre><code>{}</code></pre>\n\n", &escape(elements, false)) } else { format!( "<pre><code class=\"language-{}\">{}</code></pre>\n\n", &escape(lang.as_ref().unwrap(), false), &escape(elements, false) ) } } fn format_blockquote(elements: &[Block]) -> String { format!("<blockquote>\n{}</blockquote>\n\n", to_html(elements)) } fn format_paragraph(elements: &[Span], link_references: &LinkReferenceMap) -> String { format!("<p>{}</p>\n\n", format_spans(elements, link_references)) } fn format_header(elements: &[Span], level: usize, link_references: &LinkReferenceMap) -> String { format!( "<h{} id='{}'>{}</h{}>\n\n", level, slugify(elements, true), format_spans(elements, link_references), level ) }
use parser::Block; use parser::Block::{ Blockquote, CodeBlock, Header, Hr, LinkReference, OrderedList, Paragraph, Raw, UnorderedList, }; use parser::Span::{Break, Code, Emphasis, Image, Link, Literal, RefLink, Strong, Text}; use parser::{ListItem, OrderedListType, Span}; use regex::Regex; use std::collections::HashMap; type LinkReferenceMap<'a> = HashMap<&'a str, (&'a str, &'a Option<String>)>; fn slugify(elements: &[Span], no_spaces: bool) -> String { let mut ret = String::new(); for el in elements { let next = match *el { Break => "".to_owned(), Literal(character) => character.to_string(), Text(ref text) | Image(ref text, _, _) | Code(ref text) => text.trim().to_lowercase(), RefLink(ref content, _, _) | Link(ref content, _, _) | Strong(ref content) | Emphasis(ref content) => slugify(content, no_spaces), }; if !ret.is_empty() { ret.push('_'); } ret.push_str(&next); } if no_spaces { ret = ret.replace(" ", "_"); } ret } pub fn to_html(blocks: &[Block]) -> String { let mut ret = String::new(); let mut link_references: LinkReferenceMap = HashMap::new(); for block in blocks.iter() {
; } for block in blocks.iter() { let next = match block { Header(ref elements, level) => format_header(elements, *level, &link_references), Paragraph(ref elements) => format_paragraph(elements, &link_references), Blockquote(ref elements) => format_blockquote(elements), CodeBlock(ref lang, ref elements) => format_codeblock(lang, elements), UnorderedList(ref elements) => format_unordered_list(elements, &link_references), OrderedList(ref elements, ref num_type) => { format_ordered_list(elements, num_type, &link_references) } LinkReference(_, _, _) => "".to_owned(), Raw(ref elements) => elements.to_owned(), Hr => format!("<hr />\n\n"), }; ret.push_str(&next) } ret = ret.trim().to_owned(); ret.push('\n'); ret } fn format_spans(elements: &[Span], link_references: &LinkReferenceMap) -> String { let mut ret = String::new(); for element in elements.iter() { let next = match *element { Break => format!("<br />"), Literal(character) => character.to_string(), Text(ref text) => format!("{}", &escape(text, true)), Code(ref text) => format!("<code>{}</code>", &escape(text, false)), Link(ref content, ref url, None) => format!( "<a href=\"{}\">{}</a>", &escape(url, false), format_spans(content, link_references) ), Link(ref content, ref url, Some(ref title)) => format!( "<a href=\"{}\" title=\"{}\">{}</a>", &escape(url, false), &escape(title, true), format_spans(content, link_references) ), RefLink(ref content, ref reference, ref raw) => { if let Some((ref url, None)) = link_references.get::<str>(reference) { format!( "<a href=\"{}\">{}</a>", &escape(url, false), format_spans(content, link_references) ) } else if let Some((ref url, Some(ref title))) = link_references.get::<str>(reference) { format!( "<a href=\"{}\" title=\"{}\">{}</a>", &escape(url, false), &escape(title, true), format_spans(content, link_references) ) } else if let Some((ref url, None)) = link_references.get::<str>(&slugify(content, false)) { format!( "<a href=\"{}\">{}</a>", &escape(url, false), format_spans(content, link_references) ) } else if let Some((ref url, Some(ref title))) = link_references.get::<str>(&slugify(content, false)) { format!( "<a href=\"{}\" title=\"{}\">{}</a>", &escape(url, false), &escape(title, true), format_spans(content, link_references) ) } else { raw.to_owned() } } Image(ref text, ref url, None) => format!( "<img src=\"{}\" alt=\"{}\" />", &escape(url, false), &escape(text, true) ), Image(ref text, ref url, Some(ref title)) => format!( "<img src=\"{}\" title=\"{}\" alt=\"{}\" />", &escape(url, false), &escape(title, true), &escape(text, true) ), Emphasis(ref content) => format!("<em>{}</em>", format_spans(content, link_references)), Strong(ref content) => format!( "<strong>{}</strong>", format_spans(content, link_references) ), }; ret.push_str(&next) } ret } fn escape(text: &str, replace_entities: bool) -> String { lazy_static! { static ref AMPERSAND: Regex = Regex::new(r"&amp;(?P<x>\S+;)").unwrap(); } let replaced = text .replace("&", "&amp;") .replace("<", "&lt;") .replace("\"", "&quot;") .replace("'", "&#8217;") .replace(">", "&gt;"); if replace_entities { return AMPERSAND.replace_all(&replaced, "&$x").into_owned(); } return replaced; } fn format_list( elements: &[ListItem], start_tag: &str, end_tag: &str, link_references: &LinkReferenceMap, ) -> String { let mut ret = String::new(); for list_item in elements { let mut content = String::new(); match *list_item { ListItem::Simple(ref els) => content.push_str(&format_spans(els, link_references)), ListItem::Paragraph(ref paragraphs) => { content.push_str(&format!("\n{}", to_html(paragraphs))) } } ret.push_str(&format!("\n<li>{}</li>\n", content)) } format!("<{}>{}</{}>\n\n", start_tag, ret, end_tag) } fn format_unordered_list(elements: &[ListItem], link_references: &LinkReferenceMap) -> String { format_list(elements, "ul", "ul", link_references) } fn format_ordered_list( elements: &[ListItem], num_type: &OrderedListType, link_references: &LinkReferenceMap, ) -> String { if num_type != &OrderedListType::Numeric { format_list( elements, &format!("ol type=\"{}\"", num_type.to_str()), "ol", link_references, ) } else { format_list(elements, "ol", "ol", link_references) } } fn format_codeblock(lang: &Option<String>, elements: &str) -> String { if lang.is_none() || (lang.is_some() && lang.as_ref().unwrap().is_empty()) { format!("<pre><code>{}</code></pre>\n\n", &escape(elements, false)) } else { format!( "<pre><code class=\"language-{}\">{}</code></pre>\n\n", &escape(lang.as_ref().unwrap(), false), &escape(elements, false) ) } } fn format_blockquote(elements: &[Block]) -> String { format!("<blockquote>\n{}</blockquote>\n\n", to_html(elements)) } fn format_paragraph(elements: &[Span], link_references: &LinkReferenceMap) -> String { format!("<p>{}</p>\n\n", format_spans(elements, link_references)) } fn format_header(elements: &[Span], level: usize, link_references: &LinkReferenceMap) -> String { format!( "<h{} id='{}'>{}</h{}>\n\n", level, slugify(elements, true), format_spans(elements, link_references), level ) }
match block { LinkReference(ref id, ref text, ref title) => { link_references.insert(id, (text, title)); } _ => {} }
if_condition
[ { "content": "pub fn parse_emphasis(text: &str) -> Option<(Span, usize)> {\n\n lazy_static! {\n\n static ref EMPHASIS_UNDERSCORE: Regex = Regex::new(r\"^_(?P<text>.+?)_\").unwrap();\n\n static ref EMPHASIS_STAR: Regex = Regex::new(r\"^\\*(?P<text>.+?)\\*\").unwrap();\n\n }\n\n\n\n if EMPH...
Rust
src/network/ws/server.rs
wayfair-tremor/uring
483adf33d61a767a2de9a5ed4ed5cc272cc62ac2
use super::Reply as WsReply; use super::*; use crate::version::VERSION; use crate::{pubsub, NodeId}; use async_std::net::TcpListener; use async_std::net::ToSocketAddrs; use async_std::task; use futures::channel::mpsc::{channel, Receiver, Sender}; use futures::io::{AsyncRead, AsyncWrite}; use futures::{select, FutureExt, StreamExt}; use std::io::Error; use tungstenite::protocol::Message; use ws_proto::*; pub(crate) struct Connection { node: Node, remote_id: NodeId, protocol: Option<Protocol>, rx: Receiver<Message>, tx: Sender<Message>, ws_rx: Receiver<WsMessage>, ws_tx: Sender<WsMessage>, ps_rx: Receiver<SubscriberMsg>, ps_tx: Sender<SubscriberMsg>, } impl Connection { pub(crate) fn new(node: Node, rx: Receiver<Message>, tx: Sender<Message>) -> Self { let (ps_tx, ps_rx) = channel(crate::CHANNEL_SIZE); let (ws_tx, ws_rx) = channel(crate::CHANNEL_SIZE); Self { node, remote_id: NodeId(0), protocol: None, rx, tx, ps_tx, ps_rx, ws_tx, ws_rx, } } async fn handle_initial(&mut self, msg: Message) -> bool { self.handle_control(msg, false).await } async fn handle_control(&mut self, msg: Message, bail_on_fail: bool) -> bool { if msg.is_text() { let text = msg.into_data(); match serde_json::from_slice(&text) { Ok(ProtocolSelect::Status { rid }) => self .node .tx .send(UrMsg::Status(rid, self.ws_tx.clone())) .await .is_ok(), Ok(ProtocolSelect::Version { .. }) => self .tx .send(Message::Text(serde_json::to_string(VERSION).unwrap())) .await .is_ok(), Ok(ProtocolSelect::Select { rid, protocol }) => { self.protocol = Some(protocol); self.tx .send(Message::Text( serde_json::to_string(&ProtocolSelect::Selected { rid, protocol }) .unwrap(), )) .await .is_ok() } Ok(ProtocolSelect::Selected { .. }) => false, Ok(ProtocolSelect::As { protocol, cmd }) => match protocol { Protocol::KV => self.handle_kv_msg(serde_json::from_value(cmd).unwrap()), _ => false, }, Ok(ProtocolSelect::Subscribe { channel }) => self .node .pubsub .send(pubsub::Msg::Subscribe { channel, tx: self.ps_tx.clone(), }) .await .is_ok(), Err(e) => { if !bail_on_fail { false } else { error!( self.node.logger, "Failed to decode ProtocolSelect message: {} => {}", e, String::from_utf8(text).unwrap_or_default() ); true } } } } else { true } } async fn handle_uring(&mut self, msg: Message) -> bool { if msg.is_text() { let text = msg.into_data(); match serde_json::from_slice(&text) { Ok(CtrlMsg::Hello(id, peer)) => { info!(self.node.logger, "Hello from {}", id); self.remote_id = id; self.node .tx .unbounded_send(UrMsg::RegisterRemote(id, peer, self.ws_tx.clone())) .is_ok() } Ok(CtrlMsg::AckProposal(pid, success)) => self .node .tx .unbounded_send(UrMsg::AckProposal(pid, success)) .is_ok(), Ok(CtrlMsg::ForwardProposal(from, pid, sid, eid, value)) => self .node .tx .unbounded_send(UrMsg::ForwardProposal(from, pid, sid, eid, value)) .is_ok(), Ok(_) => true, Err(e) => { error!( self.node.logger, "Failed to decode CtrlMsg message: {} => {}", e, String::from_utf8(text).unwrap_or_default() ); false } } } else if msg.is_binary() { let bin = msg.into_data(); let msg = decode_ws(&bin); self.node.tx.unbounded_send(UrMsg::RaftMsg(msg)).is_ok() } else { true } } async fn handle_kv(&mut self, msg: Message) -> bool { if msg.is_text() { let text = msg.into_data(); match serde_json::from_slice(&text) { Ok(msg) => self.handle_kv_msg(msg), Err(e) => { error!( self.node.logger, "Failed to decode KVRequest message: {} => {}", e, String::from_utf8(text).unwrap_or_default() ); false } } } else { true } } fn handle_kv_msg(&mut self, msg: KVRequest) -> bool { match msg { KVRequest::Get { rid, key } => self .node .tx .unbounded_send(UrMsg::Get( key.into_bytes(), WsReply(rid, self.ws_tx.clone()), )) .is_ok(), KVRequest::Put { rid, key, store } => self .node .tx .unbounded_send(UrMsg::Put( key.into_bytes(), store.into_bytes(), WsReply(rid, self.ws_tx.clone()), )) .is_ok(), KVRequest::Delete { rid, key } => self .node .tx .unbounded_send(UrMsg::Delete( key.into_bytes(), WsReply(rid, self.ws_tx.clone()), )) .is_ok(), KVRequest::Cas { rid, key, check, store, } => self .node .tx .unbounded_send(UrMsg::Cas( key.into_bytes(), check.map(String::into_bytes), store.into_bytes(), WsReply(rid, self.ws_tx.clone()), )) .is_ok(), } } async fn handle_mring(&mut self, msg: Message) -> bool { if msg.is_text() { let text = msg.into_data(); match serde_json::from_slice(&text) { Ok(msg) => self.handle_mring_msg(msg).await, Err(e) => { error!( self.node.logger, "Failed to decode MRRequest message: {} => {}", e, String::from_utf8(text).unwrap_or_default() ); false } } } else { true } } async fn handle_mring_msg(&mut self, msg: MRRequest) -> bool { match msg { MRRequest::GetSize { rid } => self .node .tx .unbounded_send(UrMsg::MRingGetSize(WsReply(rid, self.ws_tx.clone()))) .is_ok(), MRRequest::SetSize { rid, size } => self .node .tx .unbounded_send(UrMsg::MRingSetSize(size, WsReply(rid, self.ws_tx.clone()))) .is_ok(), MRRequest::GetNodes { rid } => self .node .tx .unbounded_send(UrMsg::MRingGetNodes(WsReply(rid, self.ws_tx.clone()))) .is_ok(), MRRequest::AddNode { rid, node } => self .node .tx .unbounded_send(UrMsg::MRingAddNode(node, WsReply(rid, self.ws_tx.clone()))) .is_ok(), MRRequest::RemoveNode { rid, node } => self .node .tx .unbounded_send(UrMsg::MRingRemoveNode( node, WsReply(rid, self.ws_tx.clone()), )) .is_ok(), } } async fn handle_version(&mut self, msg: Message) -> bool { if msg.is_text() { let text = msg.into_data(); match serde_json::from_slice(&text) { Ok(msg) => self.handle_version_msg(msg), Err(e) => { error!( self.node.logger, "Failed to decode VRequest message: {} => {}", e, String::from_utf8(text).unwrap_or_default() ); false } } } else { true } } fn handle_version_msg(&mut self, msg: VRequest) -> bool { match msg { VRequest::Get { rid } => { self.node .tx .unbounded_send(UrMsg::Version(rid, self.ws_tx.clone())) .unwrap(); true } } } async fn handle_status(&mut self, msg: Message) -> bool { if msg.is_text() { let text = msg.into_data(); match serde_json::from_slice(&text) { Ok(msg) => self.handle_status_msg(msg), Err(e) => { error!( self.node.logger, "Failed to decode SRequest message: {} => {}", e, String::from_utf8(text).unwrap_or_default() ); false } } } else { true } } fn handle_status_msg(&mut self, msg: SRequest) -> bool { match msg { SRequest::Get { rid } => { self.node .tx .unbounded_send(UrMsg::Status(rid, self.ws_tx.clone())) .unwrap(); true } } } pub async fn msg_loop(mut self, logger: Logger) { loop { let cont = select! { msg = self.rx.next() => { if let Some(msg) = msg { let msg2 = msg.clone(); let handled_ok = match self.protocol { None => self.handle_initial(msg).await, Some(Protocol::KV) => self.handle_kv(msg).await, Some(Protocol::URing) => self.handle_uring(msg).await, Some(Protocol::MRing) => self.handle_mring(msg).await, Some(Protocol::Version) => self.handle_version(msg).await, Some(Protocol::Status) => self.handle_status(msg).await, }; handled_ok || self.handle_control(msg2, true).await } else { false } } msg = self.ws_rx.next() => { match self.protocol { None | Some(Protocol::Status) | Some(Protocol::Version) | Some(Protocol::KV) | Some(Protocol::MRing) => match msg { Some(WsMessage::Ctrl(msg)) =>self.tx.send(Message::Text(serde_json::to_string(&msg).unwrap())).await.is_ok(), Some(WsMessage::Reply(_, msg)) =>self.tx.send(Message::Text(serde_json::to_string(&msg).unwrap())).await.is_ok(), None | Some(WsMessage::Raft(_)) => false, } Some(Protocol::URing) => match msg { Some(WsMessage::Ctrl(msg)) =>self.tx.send(Message::Text(serde_json::to_string(&msg).unwrap())).await.is_ok(), Some(WsMessage::Raft(msg)) => self.tx.send(Message::Binary(encode_ws(msg).to_vec())).await.is_ok(), Some(WsMessage::Reply(_, msg)) =>self.tx.send(Message::Text(serde_json::to_string(&msg).unwrap())).await.is_ok(), None => false, }, } } msg = self.ps_rx.next() => { if let Some(msg) = msg { self.tx.send(Message::Text(serde_json::to_string(&msg).unwrap())).await.is_ok() } else { false } } complete => false }; if !cont { error!(logger, "Client connection to {} down.", self.remote_id); self.node .tx .unbounded_send(UrMsg::DownRemote(self.remote_id)) .unwrap(); break; } } } } pub(crate) async fn accept_connection<S>(logger: Logger, node: Node, stream: S) where S: AsyncRead + AsyncWrite + Unpin, { let mut ws_stream = if let Ok(ws_stream) = async_tungstenite::accept_async(stream).await { ws_stream } else { error!(logger, "Error during the websocket handshake occurred"); return; }; let (mut msg_tx, msg_rx) = channel(crate::CHANNEL_SIZE); let (response_tx, mut response_rx) = channel(crate::CHANNEL_SIZE); let c = Connection::new(node, msg_rx, response_tx); task::spawn(c.msg_loop(logger.clone())); loop { select! { message = ws_stream.next().fuse() => { if let Some(Ok(message)) = message { msg_tx .send(message).await .expect("Failed to forward request"); } else { error!(logger, "Client connection down.", ); break; } } resp = response_rx.next() => { if let Some(resp) = resp { ws_stream.send(resp).await.expect("Failed to send response"); } else { error!(logger, "Client connection down.", ); break; } } complete => { error!(logger, "Client connection down.", ); break; } } } } pub(crate) async fn run(logger: Logger, node: Node, addr: String) -> Result<(), Error> { let addr = addr .to_socket_addrs() .await .expect("Not a valid address") .next() .expect("Not a socket address"); let try_socket = TcpListener::bind(&addr).await; let listener = try_socket.expect("Failed to bind"); info!(logger, "Listening on: {}", addr); while let Ok((stream, _)) = listener.accept().await { task::spawn(accept_connection(logger.clone(), node.clone(), stream)); } Ok(()) }
use super::Reply as WsReply; use super::*; use crate::version::VERSION; use crate::{pubsub, NodeId}; use async_std::net::TcpListener; use async_std::net::ToSocketAddrs; use async_std::task; use futures::channel::mpsc::{channel, Receiver, Sender}; use futures::io::{AsyncRead, AsyncWrite}; use futures::{select, FutureExt, StreamExt}; use std::io::Error; use tungstenite::protocol::Message; use ws_proto::*; pub(crate) struct Connection { node: Node, remote_id: NodeId, protocol: Option<Protocol>, rx: Receiver<Message>, tx: Sender<Message>, ws_rx: Receiver<WsMessage>, ws_tx: Sender<WsMessage>, ps_rx: Receiver<SubscriberMsg>, ps_tx: Sender<SubscriberMsg>, } impl Connection { pub(crate) fn new(node: Node, rx: Receiver<Message>, tx: Sender<Message>) -> Self { let (ps_tx, ps_rx) = channel(crate::CHANNEL_SIZE); let (ws_tx, ws_rx) = channel(crate::CHANNEL_SIZE); Self { node, remote_id: NodeId(0), protocol: None, rx, tx, ps_tx, ps_rx, ws_tx, ws_rx, } } async fn handle_initial(&mut self, msg: Message) -> bool { self.handle_control(msg, false).await } async fn handle_control(&mut self, msg: Message, bail_on_fail: bool) -> bool { if msg.is_text() { let text = msg.into_data(); match serde_json::from_slice(&text) { Ok(ProtocolSelect::Status { rid }) => self .node .tx .send(UrMsg::Status(rid, self.ws_tx.clone())) .await .is_ok(), Ok(ProtocolSelect::Version { .. }) => self .tx .send(Message::Text(serde_json::to_string(VERSION).unwrap())) .await .is_ok(), Ok(ProtocolSelect::Select { rid, protocol }) => { self.protocol = Some(protocol); self.tx .send(Message::Text( serde_json::to_string(&ProtocolSelect::Selected { rid, protocol }) .unwrap(), )) .await .is_ok() } Ok(ProtocolSelect::Selected { .. }) => false, Ok(ProtocolSelect::As { protocol, cmd }) => match protocol { Protocol::KV => self.handle_kv_msg(serde_json::from_value(cmd).unwrap()), _ => false, }, Ok(ProtocolSelect::Subscribe { channel }) => self .node .pubsub .send(pubsub::Msg::Subscribe { channel, tx: self.ps_tx.clone(), }) .await .is_ok(), Err(e) => { if !bail_on_fail { false } else { error!( self.node.logger, "Failed to decode ProtocolSelect message: {} => {}", e, String::from_utf8(text).unwrap_or_default() ); true } } } } else { true } } async fn handle_uring(&mut self, msg: Message) -> bool { if msg.is_text() { let text = msg.into_data(); match serde_json::from_slice(&text) { Ok(CtrlMsg::Hello(id, peer)) => { info!(self.node.logger, "Hello from {}", id); self.remote_id = id; self.node .tx .unbounded_send(UrMsg::RegisterRemote(id, peer, self.ws_tx.clone())) .is_ok() } Ok(CtrlMsg::AckProposal(pid, success)) => self .node .tx .unbounded_send(UrMsg::AckProposal(pid, success)) .is_ok(), Ok(CtrlMsg::ForwardProposal(from, pid, sid, eid, value)) => self .node .tx .unbounded_send(UrMsg::ForwardProposal(from, pid, sid, eid, value)) .is_ok(), Ok(_) => true, Err(e) => { error!( self.node.logger, "Failed to decode CtrlMsg message: {} => {}", e, String::from_utf8(text).unwrap_or_default() ); false } } } else if msg.is_binary() { let bin = msg.into_data(); let msg = decode_ws(&bin); self.node.tx.unbounded_send(UrMsg::RaftMsg(msg)).is_ok() } else { true } } async fn handle_kv(&mut self, msg: Message) -> bool { if msg.is_text() { let text = msg.into_data(); match serde_json::from_slice(&text) { Ok(msg) => self.handle_kv_msg(msg), Err(e) => { error!( self.node.logger, "Failed to decode KVRequest message: {} => {}", e, String::from_utf8(text).unwrap_or_default() ); false } } } else { true } } fn handle_kv_msg(&mut self, msg: KVRequest) -> bool { match msg { KVRequest::Get { rid, key } => self .node .tx .unbounded_send(UrMsg::Get( key.into_bytes(), WsReply(rid, self.ws_tx.clone()), )) .is_ok(), KVRequest::Put { rid, key, store } => self .node .tx .unbounded_send(UrMsg::Put( key.into_bytes(), store.into_bytes(), WsReply(rid, self.ws_tx.clone()), )) .is_ok(), KVRequest::Delete { rid, key } => self .node .tx .unbounded_send(UrMsg::Delete( key.into_bytes(), WsReply(rid, self.ws_tx.clone()), )) .is_ok(), KVRequest::Cas { rid, key, check, store, } => self .node .tx .unbounded_send(UrMsg::Cas( key.into_bytes(), check.map(String::into_bytes), store.into_bytes(), WsReply(rid, self.ws_tx.clone()), )) .is_ok(), } } async fn handle_mring(&mut self, msg: Message) -> bool { if msg.is_text() { let text = msg.into_data(); match serde_json::from_slice(&text) { Ok(msg) => self.handle_mring_msg(msg).await, Err(e) => { error!( self.node.logger, "Failed to decode MRRequest message: {} => {}", e, String::from_utf8(text).unwrap_or_default() ); false } } } else { true } }
async fn handle_version(&mut self, msg: Message) -> bool { if msg.is_text() { let text = msg.into_data(); match serde_json::from_slice(&text) { Ok(msg) => self.handle_version_msg(msg), Err(e) => { error!( self.node.logger, "Failed to decode VRequest message: {} => {}", e, String::from_utf8(text).unwrap_or_default() ); false } } } else { true } } fn handle_version_msg(&mut self, msg: VRequest) -> bool { match msg { VRequest::Get { rid } => { self.node .tx .unbounded_send(UrMsg::Version(rid, self.ws_tx.clone())) .unwrap(); true } } } async fn handle_status(&mut self, msg: Message) -> bool { if msg.is_text() { let text = msg.into_data(); match serde_json::from_slice(&text) { Ok(msg) => self.handle_status_msg(msg), Err(e) => { error!( self.node.logger, "Failed to decode SRequest message: {} => {}", e, String::from_utf8(text).unwrap_or_default() ); false } } } else { true } } fn handle_status_msg(&mut self, msg: SRequest) -> bool { match msg { SRequest::Get { rid } => { self.node .tx .unbounded_send(UrMsg::Status(rid, self.ws_tx.clone())) .unwrap(); true } } } pub async fn msg_loop(mut self, logger: Logger) { loop { let cont = select! { msg = self.rx.next() => { if let Some(msg) = msg { let msg2 = msg.clone(); let handled_ok = match self.protocol { None => self.handle_initial(msg).await, Some(Protocol::KV) => self.handle_kv(msg).await, Some(Protocol::URing) => self.handle_uring(msg).await, Some(Protocol::MRing) => self.handle_mring(msg).await, Some(Protocol::Version) => self.handle_version(msg).await, Some(Protocol::Status) => self.handle_status(msg).await, }; handled_ok || self.handle_control(msg2, true).await } else { false } } msg = self.ws_rx.next() => { match self.protocol { None | Some(Protocol::Status) | Some(Protocol::Version) | Some(Protocol::KV) | Some(Protocol::MRing) => match msg { Some(WsMessage::Ctrl(msg)) =>self.tx.send(Message::Text(serde_json::to_string(&msg).unwrap())).await.is_ok(), Some(WsMessage::Reply(_, msg)) =>self.tx.send(Message::Text(serde_json::to_string(&msg).unwrap())).await.is_ok(), None | Some(WsMessage::Raft(_)) => false, } Some(Protocol::URing) => match msg { Some(WsMessage::Ctrl(msg)) =>self.tx.send(Message::Text(serde_json::to_string(&msg).unwrap())).await.is_ok(), Some(WsMessage::Raft(msg)) => self.tx.send(Message::Binary(encode_ws(msg).to_vec())).await.is_ok(), Some(WsMessage::Reply(_, msg)) =>self.tx.send(Message::Text(serde_json::to_string(&msg).unwrap())).await.is_ok(), None => false, }, } } msg = self.ps_rx.next() => { if let Some(msg) = msg { self.tx.send(Message::Text(serde_json::to_string(&msg).unwrap())).await.is_ok() } else { false } } complete => false }; if !cont { error!(logger, "Client connection to {} down.", self.remote_id); self.node .tx .unbounded_send(UrMsg::DownRemote(self.remote_id)) .unwrap(); break; } } } } pub(crate) async fn accept_connection<S>(logger: Logger, node: Node, stream: S) where S: AsyncRead + AsyncWrite + Unpin, { let mut ws_stream = if let Ok(ws_stream) = async_tungstenite::accept_async(stream).await { ws_stream } else { error!(logger, "Error during the websocket handshake occurred"); return; }; let (mut msg_tx, msg_rx) = channel(crate::CHANNEL_SIZE); let (response_tx, mut response_rx) = channel(crate::CHANNEL_SIZE); let c = Connection::new(node, msg_rx, response_tx); task::spawn(c.msg_loop(logger.clone())); loop { select! { message = ws_stream.next().fuse() => { if let Some(Ok(message)) = message { msg_tx .send(message).await .expect("Failed to forward request"); } else { error!(logger, "Client connection down.", ); break; } } resp = response_rx.next() => { if let Some(resp) = resp { ws_stream.send(resp).await.expect("Failed to send response"); } else { error!(logger, "Client connection down.", ); break; } } complete => { error!(logger, "Client connection down.", ); break; } } } } pub(crate) async fn run(logger: Logger, node: Node, addr: String) -> Result<(), Error> { let addr = addr .to_socket_addrs() .await .expect("Not a valid address") .next() .expect("Not a socket address"); let try_socket = TcpListener::bind(&addr).await; let listener = try_socket.expect("Failed to bind"); info!(logger, "Listening on: {}", addr); while let Ok((stream, _)) = listener.accept().await { task::spawn(accept_connection(logger.clone(), node.clone(), stream)); } Ok(()) }
async fn handle_mring_msg(&mut self, msg: MRRequest) -> bool { match msg { MRRequest::GetSize { rid } => self .node .tx .unbounded_send(UrMsg::MRingGetSize(WsReply(rid, self.ws_tx.clone()))) .is_ok(), MRRequest::SetSize { rid, size } => self .node .tx .unbounded_send(UrMsg::MRingSetSize(size, WsReply(rid, self.ws_tx.clone()))) .is_ok(), MRRequest::GetNodes { rid } => self .node .tx .unbounded_send(UrMsg::MRingGetNodes(WsReply(rid, self.ws_tx.clone()))) .is_ok(), MRRequest::AddNode { rid, node } => self .node .tx .unbounded_send(UrMsg::MRingAddNode(node, WsReply(rid, self.ws_tx.clone()))) .is_ok(), MRRequest::RemoveNode { rid, node } => self .node .tx .unbounded_send(UrMsg::MRingRemoveNode( node, WsReply(rid, self.ws_tx.clone()), )) .is_ok(), } }
function_block-full_function
[ { "content": "// The message can be used to initialize a raft node or not.\n\nfn is_initial_msg(msg: &Message) -> bool {\n\n let msg_type = msg.get_msg_type();\n\n msg_type == MessageType::MsgRequestVote\n\n || msg_type == MessageType::MsgRequestPreVote\n\n || (msg_type == MessageType::MsgHe...
Rust
src/visitor/model.rs
SUPERAndroidAnalyzer/abxml-rs
3140e59be09108265a7f0e214f071a34f970899c
use std::{cell::RefCell, collections::HashMap, rc::Rc}; use failure::{format_err, Error, ResultExt}; use log::error; use crate::{ chunks::{ PackageWrapper, StringTableCache, StringTableWrapper, TableTypeWrapper, TypeSpecWrapper, }, model::{ owned::Entry, Entries, Identifier, Library as LibraryTrait, LibraryBuilder, Resources as ResourcesTrait, StringTable as StringTableTrait, TypeSpec as TypeSpecTrait, }, }; use super::{ChunkVisitor, Origin}; #[derive(Default, Debug)] pub struct ModelVisitor<'a> { package_mask: u32, resources: Resources<'a>, current_spec: Option<TypeSpecWrapper<'a>>, tables: HashMap<Origin, StringTableCache<StringTableWrapper<'a>>>, } impl<'a> ModelVisitor<'a> { pub fn get_resources(&self) -> &'a Resources { &self.resources } pub fn get_mut_resources(&mut self) -> &'a mut Resources { &mut self.resources } } impl<'a> ChunkVisitor<'a> for ModelVisitor<'a> { fn visit_string_table(&mut self, string_table: StringTableWrapper<'a>, origin: Origin) { if let Origin::Global = origin { self.tables .insert(origin, StringTableCache::new(string_table)); } else { let package_id = self.package_mask.get_package(); let st_res = self .resources .get_mut_package(package_id) .and_then(|package| { package.set_string_table(StringTableCache::new(string_table), origin); Some(()) }); if st_res.is_none() { error!("Could not retrieve target package"); } } } fn visit_package(&mut self, package: PackageWrapper<'a>) { if let Ok(package_id) = package.get_id() { self.package_mask = package_id << 24; let package_id = self.package_mask.get_package(); let rp = Library::new(package); self.resources.push_package(package_id, rp); if self.tables.contains_key(&Origin::Global) { if let Some(st) = self.tables.remove(&Origin::Global) { let set_result = self.resources .get_mut_package(package_id) .and_then(|package| { package.set_string_table(st, Origin::Global); Some(()) }); if set_result.is_none() { error!( "could not set the string table because it refers to a non-existing \ package" ); } } } } } fn visit_table_type(&mut self, table_type: TableTypeWrapper<'a>) { let mut entries = Entries::new(); if let Some(ts) = &self.current_spec { let mask = ts .get_id() .and_then(|id| Ok(self.package_mask | (u32::from(id) << 16))) .unwrap_or(0); let entries_result = table_type.get_entries(); match entries_result { Ok(ventries) => { for e in &ventries { let id = mask | e.get_id(); if !e.is_empty() { entries.insert(id, e.clone()); } } } Err(err) => error!("Error visiting table_type: {}", err), } } let package_id = self.package_mask.get_package(); self.resources .get_mut_package(package_id) .and_then(|package| { package.add_entries(entries); Some(()) }); } fn visit_type_spec(&mut self, type_spec: TypeSpecWrapper<'a>) { self.current_spec = Some(type_spec.clone()); let package_id = (self.package_mask >> 24) as u8; if let Some(package) = self.resources.get_mut_package(package_id) { let _ = package .add_type_spec(type_spec) .map_err(|e| error!("Could not add type spec: {}", e)); } else { error!("Type spec refers to a non existing package"); } } } pub type RefPackage<'a> = Rc<RefCell<Library<'a>>>; #[derive(Default, Debug)] pub struct Resources<'a> { packages: HashMap<u8, Library<'a>>, main_package: Option<u8>, } impl<'a> Resources<'a> { pub fn push_package(&mut self, package_id: u8, package: Library<'a>) { if self.packages.is_empty() { self.main_package = Some(package_id); } self.packages.insert(package_id, package); } } impl<'a> ResourcesTrait<'a> for Resources<'a> { type Library = Library<'a>; fn get_package(&self, package_id: u8) -> Option<&Self::Library> { self.packages.get(&package_id) } fn get_mut_package(&mut self, package_id: u8) -> Option<&mut Self::Library> { self.packages.get_mut(&package_id) } fn get_main_package(&self) -> Option<&Self::Library> { match self.main_package { Some(package_id) => match self.packages.get(&package_id) { Some(package) => Some(package), None => None, }, _ => None, } } fn is_main_package(&self, package_id: u8) -> bool { match self.main_package { Some(pid) => pid == package_id, None => false, } } } #[derive(Debug)] pub struct Library<'a> { package: PackageWrapper<'a>, specs: HashMap<u32, TypeSpecWrapper<'a>>, string_table: Option<StringTableCache<StringTableWrapper<'a>>>, spec_string_table: Option<StringTableCache<StringTableWrapper<'a>>>, entries_string_table: Option<StringTableCache<StringTableWrapper<'a>>>, entries: Entries, } impl<'a> Library<'a> { pub fn new(package: PackageWrapper<'a>) -> Self { Self { package, specs: HashMap::new(), string_table: None, spec_string_table: None, entries_string_table: None, entries: Entries::default(), } } fn get_spec_as_str(&self, spec_id: u32) -> Result<String, Error> { if self.specs.get(&(spec_id)).is_some() { if let Some(spec_string_table) = &self.spec_string_table { if let Ok(spec_str) = spec_string_table.get_string(spec_id - 1) { return Ok((*spec_str).clone()); } } } Err(format_err!("could not retrieve spec as string")) } } impl<'a> LibraryTrait for Library<'a> { fn get_name(&self) -> Option<String> { self.package.get_name().ok() } fn format_reference( &self, id: u32, key: u32, namespace: Option<String>, prefix: &str, ) -> Result<String, Error> { let spec_id = u32::from(id.get_spec()); let spec_str = self .get_spec_as_str(spec_id) .context(format_err!("could not find spec: {}", spec_id))?; let string = self.get_entries_string(key).context(format_err!( "could not find key {} on entries string table", key ))?; let ending = if spec_str == "attr" { string } else { Rc::new(format!("{}/{}", spec_str, string)) }; match namespace { Some(ns) => Ok(format!("{}{}:{}", prefix, ns, ending)), None => Ok(format!("{}{}", prefix, ending)), } } fn get_entry(&self, id: u32) -> Result<&Entry, Error> { self.entries .get(&id) .ok_or_else(|| format_err!("could not find entry")) } fn get_entries_string(&self, str_id: u32) -> Result<Rc<String>, Error> { if let Some(string_table) = &self.entries_string_table { let out_string = string_table.get_string(str_id).context(format_err!( "could not find string {} on entries string table", str_id ))?; return Ok(out_string); } Err(format_err!("string not found on entries string table")) } fn get_spec_string(&self, str_id: u32) -> Result<Rc<String>, Error> { if let Some(string_table) = &self.spec_string_table { let out_string = string_table.get_string(str_id).context(format_err!( "could not find string {} on spec string table", str_id ))?; return Ok(out_string); } Err(format_err!("string not found on spec string table")) } } impl<'a> LibraryBuilder<'a> for Library<'a> { type StringTable = StringTableCache<StringTableWrapper<'a>>; type TypeSpec = TypeSpecWrapper<'a>; fn set_string_table(&mut self, string_table: Self::StringTable, origin: Origin) { match origin { Origin::Global => self.string_table = Some(string_table), Origin::Spec => self.spec_string_table = Some(string_table), Origin::Entries => self.entries_string_table = Some(string_table), } } fn add_entries(&mut self, entries: Entries) { self.entries.extend(entries); } fn add_type_spec(&mut self, type_spec: Self::TypeSpec) -> Result<(), Error> { let id = u32::from(type_spec.get_id()?); self.specs.insert(id, type_spec); Ok(()) } }
use std::{cell::RefCell, collections::HashMap, rc::Rc}; use failure::{format_err, Error, ResultExt}; use log::error; use crate::{ chunks::{ PackageWrapper, StringTableCache, StringTableWrapper, TableTypeWrapper, TypeSpecWrapper, }, model::{ owned::Entry, Entries, Identifier, Library as LibraryTrait, LibraryBuilder, Resources as ResourcesTrait, StringTable as StringTableTrait, TypeSpec as TypeSpecTrait, }, }; use super::{ChunkVisitor, Origin}; #[derive(Default, Debug)] pub struct ModelVisitor<'a> { package_mask: u32, resources: Resources<'a>, current_spec: Option<TypeSpecWrapper<'a>>, tables: HashMap<Origin, StringTableCache<StringTableWrapper<'a>>>, } impl<'a> ModelVisitor<'a> { pub fn get_resources(&self) -> &'a Resources { &self.resources } pub fn get_mut_resources(&mut self) -> &'a mut Resources { &mut self.resources } } impl<'a> ChunkVisitor<'a> for ModelVisitor<'a> { fn visit_string_table(&mut self, string_table: StringTableWrapper<'a>, origin: Origin) { if let Origin::Global = origin { self.tables .insert(origin, StringTableCache::new(string_table)); } else { let package_id = self.package_mask.get_package();
fn visit_package(&mut self, package: PackageWrapper<'a>) { if let Ok(package_id) = package.get_id() { self.package_mask = package_id << 24; let package_id = self.package_mask.get_package(); let rp = Library::new(package); self.resources.push_package(package_id, rp); if self.tables.contains_key(&Origin::Global) { if let Some(st) = self.tables.remove(&Origin::Global) { let set_result = self.resources .get_mut_package(package_id) .and_then(|package| { package.set_string_table(st, Origin::Global); Some(()) }); if set_result.is_none() { error!( "could not set the string table because it refers to a non-existing \ package" ); } } } } } fn visit_table_type(&mut self, table_type: TableTypeWrapper<'a>) { let mut entries = Entries::new(); if let Some(ts) = &self.current_spec { let mask = ts .get_id() .and_then(|id| Ok(self.package_mask | (u32::from(id) << 16))) .unwrap_or(0); let entries_result = table_type.get_entries(); match entries_result { Ok(ventries) => { for e in &ventries { let id = mask | e.get_id(); if !e.is_empty() { entries.insert(id, e.clone()); } } } Err(err) => error!("Error visiting table_type: {}", err), } } let package_id = self.package_mask.get_package(); self.resources .get_mut_package(package_id) .and_then(|package| { package.add_entries(entries); Some(()) }); } fn visit_type_spec(&mut self, type_spec: TypeSpecWrapper<'a>) { self.current_spec = Some(type_spec.clone()); let package_id = (self.package_mask >> 24) as u8; if let Some(package) = self.resources.get_mut_package(package_id) { let _ = package .add_type_spec(type_spec) .map_err(|e| error!("Could not add type spec: {}", e)); } else { error!("Type spec refers to a non existing package"); } } } pub type RefPackage<'a> = Rc<RefCell<Library<'a>>>; #[derive(Default, Debug)] pub struct Resources<'a> { packages: HashMap<u8, Library<'a>>, main_package: Option<u8>, } impl<'a> Resources<'a> { pub fn push_package(&mut self, package_id: u8, package: Library<'a>) { if self.packages.is_empty() { self.main_package = Some(package_id); } self.packages.insert(package_id, package); } } impl<'a> ResourcesTrait<'a> for Resources<'a> { type Library = Library<'a>; fn get_package(&self, package_id: u8) -> Option<&Self::Library> { self.packages.get(&package_id) } fn get_mut_package(&mut self, package_id: u8) -> Option<&mut Self::Library> { self.packages.get_mut(&package_id) } fn get_main_package(&self) -> Option<&Self::Library> { match self.main_package { Some(package_id) => match self.packages.get(&package_id) { Some(package) => Some(package), None => None, }, _ => None, } } fn is_main_package(&self, package_id: u8) -> bool { match self.main_package { Some(pid) => pid == package_id, None => false, } } } #[derive(Debug)] pub struct Library<'a> { package: PackageWrapper<'a>, specs: HashMap<u32, TypeSpecWrapper<'a>>, string_table: Option<StringTableCache<StringTableWrapper<'a>>>, spec_string_table: Option<StringTableCache<StringTableWrapper<'a>>>, entries_string_table: Option<StringTableCache<StringTableWrapper<'a>>>, entries: Entries, } impl<'a> Library<'a> { pub fn new(package: PackageWrapper<'a>) -> Self { Self { package, specs: HashMap::new(), string_table: None, spec_string_table: None, entries_string_table: None, entries: Entries::default(), } } fn get_spec_as_str(&self, spec_id: u32) -> Result<String, Error> { if self.specs.get(&(spec_id)).is_some() { if let Some(spec_string_table) = &self.spec_string_table { if let Ok(spec_str) = spec_string_table.get_string(spec_id - 1) { return Ok((*spec_str).clone()); } } } Err(format_err!("could not retrieve spec as string")) } } impl<'a> LibraryTrait for Library<'a> { fn get_name(&self) -> Option<String> { self.package.get_name().ok() } fn format_reference( &self, id: u32, key: u32, namespace: Option<String>, prefix: &str, ) -> Result<String, Error> { let spec_id = u32::from(id.get_spec()); let spec_str = self .get_spec_as_str(spec_id) .context(format_err!("could not find spec: {}", spec_id))?; let string = self.get_entries_string(key).context(format_err!( "could not find key {} on entries string table", key ))?; let ending = if spec_str == "attr" { string } else { Rc::new(format!("{}/{}", spec_str, string)) }; match namespace { Some(ns) => Ok(format!("{}{}:{}", prefix, ns, ending)), None => Ok(format!("{}{}", prefix, ending)), } } fn get_entry(&self, id: u32) -> Result<&Entry, Error> { self.entries .get(&id) .ok_or_else(|| format_err!("could not find entry")) } fn get_entries_string(&self, str_id: u32) -> Result<Rc<String>, Error> { if let Some(string_table) = &self.entries_string_table { let out_string = string_table.get_string(str_id).context(format_err!( "could not find string {} on entries string table", str_id ))?; return Ok(out_string); } Err(format_err!("string not found on entries string table")) } fn get_spec_string(&self, str_id: u32) -> Result<Rc<String>, Error> { if let Some(string_table) = &self.spec_string_table { let out_string = string_table.get_string(str_id).context(format_err!( "could not find string {} on spec string table", str_id ))?; return Ok(out_string); } Err(format_err!("string not found on spec string table")) } } impl<'a> LibraryBuilder<'a> for Library<'a> { type StringTable = StringTableCache<StringTableWrapper<'a>>; type TypeSpec = TypeSpecWrapper<'a>; fn set_string_table(&mut self, string_table: Self::StringTable, origin: Origin) { match origin { Origin::Global => self.string_table = Some(string_table), Origin::Spec => self.spec_string_table = Some(string_table), Origin::Entries => self.entries_string_table = Some(string_table), } } fn add_entries(&mut self, entries: Entries) { self.entries.extend(entries); } fn add_type_spec(&mut self, type_spec: Self::TypeSpec) -> Result<(), Error> { let id = u32::from(type_spec.get_id()?); self.specs.insert(id, type_spec); Ok(()) } }
let st_res = self .resources .get_mut_package(package_id) .and_then(|package| { package.set_string_table(StringTableCache::new(string_table), origin); Some(()) }); if st_res.is_none() { error!("Could not retrieve target package"); } } }
function_block-function_prefix_line
[ { "content": "pub trait Identifier {\n\n fn get_package(&self) -> u8;\n\n fn get_spec(&self) -> u8;\n\n fn get_id(&self) -> u16;\n\n}\n\n\n\nimpl Identifier for u32 {\n\n fn get_package(&self) -> u8 {\n\n let mut package_id = (self >> 24) as u8;\n\n\n\n if package_id == 0 {\n\n ...
Rust
benches/main_all/baking/fib.rs
julien-lange/mpst_rust_github
ca10d860f06d3bc4b6d1a9df290d2812235b456f
use criterion::{black_box, criterion_group, criterion_main, Criterion}; use mpstthree::binary::struct_trait::{end::End, recv::Recv, send::Send, session::Session}; use mpstthree::bundle_impl_with_enum_and_cancel; use mpstthree::role::broadcast::RoleBroadcast; use mpstthree::role::end::RoleEnd; use std::error::Error; bundle_impl_with_enum_and_cancel!(MeshedChannelsThree, A, B, C); type NameA = RoleA<RoleEnd>; type NameB = RoleB<RoleEnd>; type NameC = RoleC<RoleEnd>; type Choose0fromAtoB = <RecursBtoA as Session>::Dual; type Choose0fromAtoC = <RecursCtoA as Session>::Dual; enum Branching0fromAtoB { More( MeshedChannelsThree< Recv<i64, Send<i64, RecursBtoA>>, End, RoleA<RoleA<RoleA<RoleEnd>>>, NameB, >, ), Done(MeshedChannelsThree<End, End, RoleEnd, NameB>), } type RecursBtoA = Recv<Branching0fromAtoB, End>; enum Branching0fromAtoC { More(MeshedChannelsThree<RecursCtoA, End, RoleA<RoleEnd>, NameC>), Done(MeshedChannelsThree<End, End, RoleEnd, NameC>), } type RecursCtoA = Recv<Branching0fromAtoC, End>; type EndpointA = MeshedChannelsThree<Choose0fromAtoB, Choose0fromAtoC, RoleBroadcast, NameA>; type EndpointAMore = MeshedChannelsThree< Send<i64, Recv<i64, Choose0fromAtoB>>, Choose0fromAtoC, RoleB<RoleB<RoleBroadcast>>, NameA, >; type EndpointB = MeshedChannelsThree<RecursBtoA, End, RoleA<RoleEnd>, NameB>; type EndpointC = MeshedChannelsThree<RecursCtoA, End, RoleA<RoleEnd>, NameC>; fn endpoint_a(s: EndpointA) -> Result<(), Box<dyn Error>> { recurs_a(s, LOOPS, 1) } fn recurs_a(s: EndpointA, index: i64, old: i64) -> Result<(), Box<dyn Error>> { match index { 0 => { let s = choose_mpst_a_to_all!(s, Branching0fromAtoB::Done, Branching0fromAtoC::Done); s.close() } i => { let s: EndpointAMore = choose_mpst_a_to_all!(s, Branching0fromAtoB::More, Branching0fromAtoC::More); let s = s.send(old)?; let (new, s) = s.recv()?; recurs_a(s, i - 1, new) } } } fn endpoint_b(s: EndpointB) -> Result<(), Box<dyn Error>> { recurs_b(s, 0) } fn recurs_b(s: EndpointB, old: i64) -> Result<(), Box<dyn Error>> { offer_mpst!(s, { Branching0fromAtoB::Done(s) => { s.close() }, Branching0fromAtoB::More(s) => { let (new, s) = s.recv()?; let s = s.send(new + old)?; recurs_b(s, new + old) }, }) } fn endpoint_c(s: EndpointC) -> Result<(), Box<dyn Error>> { offer_mpst!(s, { Branching0fromAtoC::Done(s) => { s.close() }, Branching0fromAtoC::More(s) => { endpoint_c(s) }, }) } fn all_mpst() { let (thread_a, thread_b, thread_c) = fork_mpst( black_box(endpoint_a), black_box(endpoint_b), black_box(endpoint_c), ); thread_a.join().unwrap(); thread_b.join().unwrap(); thread_c.join().unwrap(); } static LOOPS: i64 = 20; fn fibo_mpst(c: &mut Criterion) { c.bench_function(&format!("Fibo MPST {} baking", LOOPS), |b| b.iter(all_mpst)); } criterion_group! { name = fib; config = Criterion::default().significance_level(0.1).sample_size(10100); targets = fibo_mpst } criterion_main!(fib);
use criterion::{black_box, criterion_group, criterion_main, Criterion}; use mpstthree::binary::struct_trait::{end::End, recv::Recv, send::Send, session::Session}; use mpstthr
e NameA = RoleA<RoleEnd>; type NameB = RoleB<RoleEnd>; type NameC = RoleC<RoleEnd>; type Choose0fromAtoB = <RecursBtoA as Session>::Dual; type Choose0fromAtoC = <RecursCtoA as Session>::Dual; enum Branching0fromAtoB { More( MeshedChannelsThree< Recv<i64, Send<i64, RecursBtoA>>, End, RoleA<RoleA<RoleA<RoleEnd>>>, NameB, >, ), Done(MeshedChannelsThree<End, End, RoleEnd, NameB>), } type RecursBtoA = Recv<Branching0fromAtoB, End>; enum Branching0fromAtoC { More(MeshedChannelsThree<RecursCtoA, End, RoleA<RoleEnd>, NameC>), Done(MeshedChannelsThree<End, End, RoleEnd, NameC>), } type RecursCtoA = Recv<Branching0fromAtoC, End>; type EndpointA = MeshedChannelsThree<Choose0fromAtoB, Choose0fromAtoC, RoleBroadcast, NameA>; type EndpointAMore = MeshedChannelsThree< Send<i64, Recv<i64, Choose0fromAtoB>>, Choose0fromAtoC, RoleB<RoleB<RoleBroadcast>>, NameA, >; type EndpointB = MeshedChannelsThree<RecursBtoA, End, RoleA<RoleEnd>, NameB>; type EndpointC = MeshedChannelsThree<RecursCtoA, End, RoleA<RoleEnd>, NameC>; fn endpoint_a(s: EndpointA) -> Result<(), Box<dyn Error>> { recurs_a(s, LOOPS, 1) } fn recurs_a(s: EndpointA, index: i64, old: i64) -> Result<(), Box<dyn Error>> { match index { 0 => { let s = choose_mpst_a_to_all!(s, Branching0fromAtoB::Done, Branching0fromAtoC::Done); s.close() } i => { let s: EndpointAMore = choose_mpst_a_to_all!(s, Branching0fromAtoB::More, Branching0fromAtoC::More); let s = s.send(old)?; let (new, s) = s.recv()?; recurs_a(s, i - 1, new) } } } fn endpoint_b(s: EndpointB) -> Result<(), Box<dyn Error>> { recurs_b(s, 0) } fn recurs_b(s: EndpointB, old: i64) -> Result<(), Box<dyn Error>> { offer_mpst!(s, { Branching0fromAtoB::Done(s) => { s.close() }, Branching0fromAtoB::More(s) => { let (new, s) = s.recv()?; let s = s.send(new + old)?; recurs_b(s, new + old) }, }) } fn endpoint_c(s: EndpointC) -> Result<(), Box<dyn Error>> { offer_mpst!(s, { Branching0fromAtoC::Done(s) => { s.close() }, Branching0fromAtoC::More(s) => { endpoint_c(s) }, }) } fn all_mpst() { let (thread_a, thread_b, thread_c) = fork_mpst( black_box(endpoint_a), black_box(endpoint_b), black_box(endpoint_c), ); thread_a.join().unwrap(); thread_b.join().unwrap(); thread_c.join().unwrap(); } static LOOPS: i64 = 20; fn fibo_mpst(c: &mut Criterion) { c.bench_function(&format!("Fibo MPST {} baking", LOOPS), |b| b.iter(all_mpst)); } criterion_group! { name = fib; config = Criterion::default().significance_level(0.1).sample_size(10100); targets = fibo_mpst } criterion_main!(fib);
ee::bundle_impl_with_enum_and_cancel; use mpstthree::role::broadcast::RoleBroadcast; use mpstthree::role::end::RoleEnd; use std::error::Error; bundle_impl_with_enum_and_cancel!(MeshedChannelsThree, A, B, C); typ
random
[ { "content": "fn smtp_main(c: &mut Criterion) {\n\n c.bench_function(&\"SMTP\".to_string(), |b| b.iter(all_mpst));\n\n}\n\n\n\ncriterion_group! {\n\n name = smtp;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = smtp_main\n\n}\n\n\n\ncriterion_main!(smtp);\...
Rust
src/db.rs
zbtzbtzbt/risinglight
38482e05b1a89690d610c8aeddaa2f6be13b18b1
use std::sync::Arc; use futures::TryStreamExt; use risinglight_proto::rowset::block_statistics::BlockStatisticsType; use tracing::debug; use crate::array::{ArrayBuilder, ArrayBuilderImpl, DataChunk, I32ArrayBuilder, Utf8ArrayBuilder}; use crate::binder::{BindError, Binder}; use crate::catalog::RootCatalogRef; use crate::executor::{ExecutorBuilder, ExecutorError}; use crate::logical_planner::{LogicalPlanError, LogicalPlaner}; use crate::optimizer::logical_plan_rewriter::{InputRefResolver, PlanRewriter}; use crate::optimizer::plan_nodes::PlanRef; use crate::optimizer::Optimizer; use crate::parser::{parse, ParserError}; use crate::storage::{ InMemoryStorage, SecondaryStorage, SecondaryStorageOptions, Storage, StorageColumnRef, StorageImpl, Table, }; pub struct Database { catalog: RootCatalogRef, executor_builder: ExecutorBuilder, storage: StorageImpl, } impl Database { pub fn new_in_memory() -> Self { let storage = InMemoryStorage::new(); let catalog = storage.catalog().clone(); let storage = StorageImpl::InMemoryStorage(Arc::new(storage)); let execution_manager = ExecutorBuilder::new(storage.clone()); Database { catalog, executor_builder: execution_manager, storage, } } pub async fn new_on_disk(options: SecondaryStorageOptions) -> Self { let storage = Arc::new(SecondaryStorage::open(options).await.unwrap()); storage.spawn_compactor().await; let catalog = storage.catalog().clone(); let storage = StorageImpl::SecondaryStorage(storage); let execution_manager = ExecutorBuilder::new(storage.clone()); Database { catalog, executor_builder: execution_manager, storage, } } pub async fn shutdown(&self) -> Result<(), Error> { if let StorageImpl::SecondaryStorage(storage) = &self.storage { storage.shutdown().await?; } Ok(()) } fn run_dt(&self) -> Result<Vec<DataChunk>, Error> { let mut db_id_vec = I32ArrayBuilder::new(); let mut db_vec = Utf8ArrayBuilder::new(); let mut schema_id_vec = I32ArrayBuilder::new(); let mut schema_vec = Utf8ArrayBuilder::new(); let mut table_id_vec = I32ArrayBuilder::new(); let mut table_vec = Utf8ArrayBuilder::new(); for (_, database) in self.catalog.all_databases() { for (_, schema) in database.all_schemas() { for (_, table) in schema.all_tables() { db_id_vec.push(Some(&(database.id() as i32))); db_vec.push(Some(&database.name())); schema_id_vec.push(Some(&(schema.id() as i32))); schema_vec.push(Some(&schema.name())); table_id_vec.push(Some(&(table.id() as i32))); table_vec.push(Some(&table.name())); } } } let vecs: Vec<ArrayBuilderImpl> = vec![ db_id_vec.into(), db_vec.into(), schema_id_vec.into(), schema_vec.into(), table_id_vec.into(), table_vec.into(), ]; Ok(vec![DataChunk::from_iter(vecs.into_iter())]) } pub async fn run_internal(&self, cmd: &str) -> Result<Vec<DataChunk>, Error> { if let Some((cmd, arg)) = cmd.split_once(' ') { if cmd == "stat" { if let StorageImpl::SecondaryStorage(ref storage) = self.storage { let (table, col) = arg.split_once(' ').expect("failed to parse command"); let table_id = self .catalog .get_table_id_by_name("postgres", "postgres", table) .expect("table not found"); let col_id = self .catalog .get_table(&table_id) .unwrap() .get_column_id_by_name(col) .expect("column not found"); let table = storage.get_table(table_id)?; let txn = table.read().await?; let row_count = txn.aggreagate_block_stat(&[ ( BlockStatisticsType::RowCount, StorageColumnRef::Idx(col_id), ), ( BlockStatisticsType::DistinctValue, StorageColumnRef::Idx(col_id), ), ]); let mut stat_name = Utf8ArrayBuilder::with_capacity(2); let mut stat_value = Utf8ArrayBuilder::with_capacity(2); stat_name.push(Some("RowCount")); stat_value.push(Some( row_count[0] .as_usize() .unwrap() .unwrap() .to_string() .as_str(), )); stat_name.push(Some("DistinctValue")); stat_value.push(Some( row_count[1] .as_usize() .unwrap() .unwrap() .to_string() .as_str(), )); Ok(vec![DataChunk::from_iter([ ArrayBuilderImpl::from(stat_name), ArrayBuilderImpl::from(stat_value), ])]) } else { Err(Error::InternalError( "this storage engine doesn't support statistics".to_string(), )) } } else { Err(Error::InternalError("unsupported command".to_string())) } } else if cmd == "dt" { self.run_dt() } else { Err(Error::InternalError("unsupported command".to_string())) } } pub async fn run(&self, sql: &str) -> Result<Vec<DataChunk>, Error> { if let Some(cmdline) = sql.strip_prefix('\\') { return self.run_internal(cmdline).await; } let stmts = parse(sql)?; let mut binder = Binder::new(self.catalog.clone()); let logical_planner = LogicalPlaner::default(); let mut optimizer = Optimizer { enable_filter_scan: self.storage.enable_filter_scan(), }; let mut outputs = vec![]; for stmt in stmts { let stmt = binder.bind(&stmt)?; debug!("{:#?}", stmt); let logical_plan = logical_planner.plan(stmt)?; debug!("{:#?}", logical_plan); let mut input_ref_resolver = InputRefResolver::default(); let logical_plan = input_ref_resolver.rewrite(logical_plan); let column_names = logical_plan.out_names(); debug!("{:#?}", logical_plan); let optimized_plan = optimizer.optimize(logical_plan); debug!("{:#?}", optimized_plan); let executor = self.executor_builder.clone().build(optimized_plan); let mut output: Vec<DataChunk> = executor.try_collect().await.map_err(|e| { debug!("error: {}", e); e })?; for chunk in &output { debug!("output:\n{}", chunk); } if !column_names.is_empty() && !output.is_empty() { output[0].set_header(column_names); } outputs.extend(output); } Ok(outputs) } pub fn generate_execution_plan(&self, sql: &str) -> Result<Vec<PlanRef>, Error> { let stmts = parse(sql)?; let mut binder = Binder::new(self.catalog.clone()); let logical_planner = LogicalPlaner::default(); let mut optimizer = Optimizer { enable_filter_scan: self.storage.enable_filter_scan(), }; let mut plans = vec![]; for stmt in stmts { let stmt = binder.bind(&stmt)?; debug!("{:#?}", stmt); let logical_plan = logical_planner.plan(stmt)?; debug!("{:#?}", logical_plan); let mut input_ref_resolver = InputRefResolver::default(); let logical_plan = input_ref_resolver.rewrite(logical_plan); debug!("{:#?}", logical_plan); let optimized_plan = optimizer.optimize(logical_plan); debug!("{:#?}", optimized_plan); plans.push(optimized_plan); } Ok(plans) } } #[derive(thiserror::Error, Debug)] pub enum Error { #[error("parse error: {0}")] Parse( #[source] #[from] ParserError, ), #[error("bind error: {0}")] Bind( #[source] #[from] BindError, ), #[error("logical plan error: {0}")] Plan( #[source] #[from] LogicalPlanError, ), #[error("execute error: {0}")] Execute( #[source] #[from] ExecutorError, ), #[error("Storage error: {0}")] StorageError( #[source] #[from] #[backtrace] crate::storage::TracedStorageError, ), #[error("Internal error: {0}")] InternalError(String), }
use std::sync::Arc; use futures::TryStreamExt; use risinglight_proto::rowset::block_statistics::BlockStatisticsType; use tracing::debug; use crate::array::{ArrayBuilder, ArrayBuilderImpl, DataChunk, I32ArrayBuilder, Utf8ArrayBuilder}; use crate::binder::{BindError, Binder}; use crate::catalog::RootCatalogRef; use crate::executor::{ExecutorBuilder, ExecutorError}; use crate::logical_planner::{LogicalPlanError, LogicalPlaner}; use crate::optimizer::logical_plan_rewriter::{InputRefResolver, PlanRewriter}; use crate::optimizer::plan_nodes::PlanRef; use crate::optimizer::Optimizer; use crate::parser::{parse, ParserError}; use crate::storage::{ InMemoryStorage, SecondaryStorage, SecondaryStorageOptions, Storage, StorageColumnRef, StorageImpl, Table, }; pub struct Database { catalog: RootCatalogRef, executor_builder: ExecutorBuilder, storage: StorageImpl, } impl Database { pub fn new_in_memory() -> Self { let storage = InMemoryStorage::new(); let catalog = storage.catalog().clone(); let storage = StorageImpl::InMemoryStorage(Arc::new(storage)); let execution_manager = ExecutorBuilder::new(storage.clone()); Database { catalog, executor_builder: execution_manager, storage, } }
pub async fn shutdown(&self) -> Result<(), Error> { if let StorageImpl::SecondaryStorage(storage) = &self.storage { storage.shutdown().await?; } Ok(()) } fn run_dt(&self) -> Result<Vec<DataChunk>, Error> { let mut db_id_vec = I32ArrayBuilder::new(); let mut db_vec = Utf8ArrayBuilder::new(); let mut schema_id_vec = I32ArrayBuilder::new(); let mut schema_vec = Utf8ArrayBuilder::new(); let mut table_id_vec = I32ArrayBuilder::new(); let mut table_vec = Utf8ArrayBuilder::new(); for (_, database) in self.catalog.all_databases() { for (_, schema) in database.all_schemas() { for (_, table) in schema.all_tables() { db_id_vec.push(Some(&(database.id() as i32))); db_vec.push(Some(&database.name())); schema_id_vec.push(Some(&(schema.id() as i32))); schema_vec.push(Some(&schema.name())); table_id_vec.push(Some(&(table.id() as i32))); table_vec.push(Some(&table.name())); } } } let vecs: Vec<ArrayBuilderImpl> = vec![ db_id_vec.into(), db_vec.into(), schema_id_vec.into(), schema_vec.into(), table_id_vec.into(), table_vec.into(), ]; Ok(vec![DataChunk::from_iter(vecs.into_iter())]) } pub async fn run_internal(&self, cmd: &str) -> Result<Vec<DataChunk>, Error> { if let Some((cmd, arg)) = cmd.split_once(' ') { if cmd == "stat" { if let StorageImpl::SecondaryStorage(ref storage) = self.storage { let (table, col) = arg.split_once(' ').expect("failed to parse command"); let table_id = self .catalog .get_table_id_by_name("postgres", "postgres", table) .expect("table not found"); let col_id = self .catalog .get_table(&table_id) .unwrap() .get_column_id_by_name(col) .expect("column not found"); let table = storage.get_table(table_id)?; let txn = table.read().await?; let row_count = txn.aggreagate_block_stat(&[ ( BlockStatisticsType::RowCount, StorageColumnRef::Idx(col_id), ), ( BlockStatisticsType::DistinctValue, StorageColumnRef::Idx(col_id), ), ]); let mut stat_name = Utf8ArrayBuilder::with_capacity(2); let mut stat_value = Utf8ArrayBuilder::with_capacity(2); stat_name.push(Some("RowCount")); stat_value.push(Some( row_count[0] .as_usize() .unwrap() .unwrap() .to_string() .as_str(), )); stat_name.push(Some("DistinctValue")); stat_value.push(Some( row_count[1] .as_usize() .unwrap() .unwrap() .to_string() .as_str(), )); Ok(vec![DataChunk::from_iter([ ArrayBuilderImpl::from(stat_name), ArrayBuilderImpl::from(stat_value), ])]) } else { Err(Error::InternalError( "this storage engine doesn't support statistics".to_string(), )) } } else { Err(Error::InternalError("unsupported command".to_string())) } } else if cmd == "dt" { self.run_dt() } else { Err(Error::InternalError("unsupported command".to_string())) } } pub async fn run(&self, sql: &str) -> Result<Vec<DataChunk>, Error> { if let Some(cmdline) = sql.strip_prefix('\\') { return self.run_internal(cmdline).await; } let stmts = parse(sql)?; let mut binder = Binder::new(self.catalog.clone()); let logical_planner = LogicalPlaner::default(); let mut optimizer = Optimizer { enable_filter_scan: self.storage.enable_filter_scan(), }; let mut outputs = vec![]; for stmt in stmts { let stmt = binder.bind(&stmt)?; debug!("{:#?}", stmt); let logical_plan = logical_planner.plan(stmt)?; debug!("{:#?}", logical_plan); let mut input_ref_resolver = InputRefResolver::default(); let logical_plan = input_ref_resolver.rewrite(logical_plan); let column_names = logical_plan.out_names(); debug!("{:#?}", logical_plan); let optimized_plan = optimizer.optimize(logical_plan); debug!("{:#?}", optimized_plan); let executor = self.executor_builder.clone().build(optimized_plan); let mut output: Vec<DataChunk> = executor.try_collect().await.map_err(|e| { debug!("error: {}", e); e })?; for chunk in &output { debug!("output:\n{}", chunk); } if !column_names.is_empty() && !output.is_empty() { output[0].set_header(column_names); } outputs.extend(output); } Ok(outputs) } pub fn generate_execution_plan(&self, sql: &str) -> Result<Vec<PlanRef>, Error> { let stmts = parse(sql)?; let mut binder = Binder::new(self.catalog.clone()); let logical_planner = LogicalPlaner::default(); let mut optimizer = Optimizer { enable_filter_scan: self.storage.enable_filter_scan(), }; let mut plans = vec![]; for stmt in stmts { let stmt = binder.bind(&stmt)?; debug!("{:#?}", stmt); let logical_plan = logical_planner.plan(stmt)?; debug!("{:#?}", logical_plan); let mut input_ref_resolver = InputRefResolver::default(); let logical_plan = input_ref_resolver.rewrite(logical_plan); debug!("{:#?}", logical_plan); let optimized_plan = optimizer.optimize(logical_plan); debug!("{:#?}", optimized_plan); plans.push(optimized_plan); } Ok(plans) } } #[derive(thiserror::Error, Debug)] pub enum Error { #[error("parse error: {0}")] Parse( #[source] #[from] ParserError, ), #[error("bind error: {0}")] Bind( #[source] #[from] BindError, ), #[error("logical plan error: {0}")] Plan( #[source] #[from] LogicalPlanError, ), #[error("execute error: {0}")] Execute( #[source] #[from] ExecutorError, ), #[error("Storage error: {0}")] StorageError( #[source] #[from] #[backtrace] crate::storage::TracedStorageError, ), #[error("Internal error: {0}")] InternalError(String), }
pub async fn new_on_disk(options: SecondaryStorageOptions) -> Self { let storage = Arc::new(SecondaryStorage::open(options).await.unwrap()); storage.spawn_compactor().await; let catalog = storage.catalog().clone(); let storage = StorageImpl::SecondaryStorage(storage); let execution_manager = ExecutorBuilder::new(storage.clone()); Database { catalog, executor_builder: execution_manager, storage, } }
function_block-full_function
[ { "content": "pub fn path_of_index_column(base: impl AsRef<Path>, column_info: &ColumnCatalog) -> PathBuf {\n\n path_of_column(base, column_info, \".idx\")\n\n}\n\n\n", "file_path": "src/storage/secondary/rowset/rowset_builder.rs", "rank": 0, "score": 193341.85560012443 }, { "content": "p...
Rust
bc/wallets_macro/src/lib.rs
scryinfo/cashbox
667b89c4b3107b9229c3758bf9f8266316dac08f
use proc_macro::TokenStream; use proc_macro_roids::{DeriveInputStructExt, FieldsNamedAppend}; use quote::quote; use syn::{AttributeArgs, DeriveInput, Fields, FieldsNamed, parse_macro_input, parse_quote, Type}; mod db_meta; mod cr; #[proc_macro_attribute] pub fn db_append_shared(args: TokenStream, input: TokenStream) -> TokenStream { let mut ast = parse_macro_input!(input as DeriveInput); let args = parse_macro_input!(args as AttributeArgs); let fields_additional: FieldsNamed = parse_quote!({ #[serde(default)] pub id: String, #[serde(default)] pub create_time: i64, #[serde(default)] pub update_time: i64, }); ast.append_named(fields_additional); let name = &ast.ident; let imp_base = quote! { impl Shared for #name { fn get_id(&self) -> String { self.id.clone() } fn set_id(&mut self, id: String) { self.id = id; } fn get_create_time(&self) -> i64 { self.create_time } fn set_create_time(&mut self, create_time: i64) { self.create_time = create_time; } fn get_update_time(&self) -> i64 { self.update_time } fn set_update_time(&mut self, update_time: i64) { self.update_time = update_time; } } }; let impl_crud = if args.is_empty() { quote! {} } else { quote! { impl CRUDTable for #name { type IdType = String; fn get_id(&self) -> Option<&Self::IdType>{ if self.id.is_empty() { None }else{ Some(&self.id) } } } } }; let fields_stream = db_field_name(&ast.ident, &ast.fields()); let gen = TokenStream::from(quote! { #ast #fields_stream #imp_base #impl_crud }); if cfg!(feature = "print_macro") { println!("\n............gen impl db_append_shared {}:\n {}", name, gen); } if cfg!(feature = "db_meta") { let mut meta = db_meta::DbMeta::get().lock().expect("db_meta::DbMeta::get().lock()"); (*meta).push(&ast); } gen } #[proc_macro_attribute] pub fn db_sub_struct(_: TokenStream, input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let fields_stream = db_field_name(&ast.ident, &ast.fields()); let gen = TokenStream::from(quote! { #ast #fields_stream }); if cfg!(feature = "print_macro") { println!("\n////// gen impl db_sub_struct {}:\n {}", &ast.ident.to_string(), gen); } if cfg!(feature = "db_meta") { let mut meta = db_meta::DbMeta::get().lock().expect("db_meta::DbMeta::get().lock()"); (*meta).push_sub_struct(&ast); } gen } fn db_field_name(name: &syn::Ident, fields: &Fields) -> proc_macro2::TokenStream { let fields_stream = { let mut fields_vec = Vec::new(); for f in fields { let field_ident = &f.ident; if let Some(id) = &f.ident { let field_name = id.to_string(); fields_vec.push(quote! {pub const #field_ident : &'a str = #field_name; }); } } if fields_vec.is_empty() { quote! {} } else { quote! { #[allow(non_upper_case_globals)] impl<'a> #name { #(#fields_vec)* } } } }; fields_stream } #[proc_macro_derive(DbBeforeSave)] pub fn db_before_save(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let name = &ast.ident; let gen = quote! { impl dao::BeforeSave for #name { fn before_save(&mut self){ if Shared::get_id(self).is_empty() { self.set_id(kits::uuid()); self.set_update_time(kits::now_ts_seconds()); self.set_create_time(self.get_update_time()); } else { self.set_update_time(kits::now_ts_seconds()); } } } }; if cfg!(feature = "print_macro") { println!("\n............gen impl DbBeforeSave {}:\n {}", name, gen); } gen.into() } #[proc_macro_derive(DbBeforeUpdate)] pub fn db_before_update(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let name = &ast.ident; let gen = quote! { impl dao::BeforeUpdate for #name { fn before_update(&mut self){ self.set_update_time(kits::now_ts_seconds()); } } }; if cfg!(feature = "print_macro") { println!("\n............gen impl DbBeforeUpdate {}:\n {}", name, gen); } gen.into() } #[proc_macro_derive(DlStruct)] pub fn dl_struct(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let name = &ast.ident; let mut drops = Vec::new(); for field in ast.fields().iter() { if let (Type::Ptr(_), Some(ident)) = (&field.ty, field.ident.as_ref()) { let fname = ident; drops.push(quote! { self.#fname.free(); }); } } let gen = TokenStream::from(quote! { impl CStruct for #name { fn free(&mut self) { #(#drops)* } } impl Drop for #name { fn drop(&mut self) { self.free(); } } }); if cfg!(feature = "print_macro") { println!("\n............gen impl dl_struct {}:\n {}", name, gen); } gen } #[proc_macro_derive(DlDefault)] pub fn dl_default(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let name = &ast.ident; let mut drops = Vec::new(); for field in ast.fields().iter() { if let Some(ident) = field.ident.as_ref() { let fname = ident; if let Type::Ptr(_) = &field.ty { drops.push(quote! { #fname : std::ptr::null_mut() }); } else { drops.push(quote! { #fname : Default::default() }); } } } let gen = TokenStream::from(quote! { impl Default for #name { fn default() -> Self { #name { #(#drops,)* } } } }); if cfg!(feature = "print_macro") { println!("............gen impl dl_default {}:\n {}", name, gen); } gen } #[proc_macro_derive(DlCR)] pub fn dl_cr(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); cr::dl_cr(&ast.ident.to_string(), &ast.fields()) } #[proc_macro_derive(DlDrop)] pub fn dl_drop(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let name = &ast.ident; let gen = TokenStream::from(quote! { impl Drop for #name { fn drop(&mut self) { self.free(); } } }); if cfg!(feature = "print_macro") { println!("............gen impl dl_drop {}:\n {}", name, gen); } gen } pub(crate) fn to_snake_name(name: &String) -> String { let chs = name.chars(); let mut new_name = String::new(); let mut index = 0; let chs_len = name.len(); for x in chs { if x.is_uppercase() { if index != 0 && (index + 1) != chs_len { new_name.push_str("_"); } new_name.push_str(x.to_lowercase().to_string().as_str()); } else { new_name.push(x); } index += 1; } return new_name; } #[cfg(test)] mod tests { use syn::{Fields, FieldsNamed, parse_quote, Type}; #[test] fn it_works() { let fields_named: FieldsNamed = parse_quote! {{ pub id: *mut c_char, pub count: u32, pub name: *mut c_char, pub next: *mut Dl, }}; let fields = Fields::from(fields_named); let mut count = 0; for field in fields.iter() { if let Type::Ptr(_) = field.ty { count += 1; println!("\nttt: {}, {}", field.ident.as_ref().unwrap().to_string(), "raw ptr"); } } assert_eq!(3, count); } }
use proc_macro::TokenStream; use proc_macro_roids::{DeriveInputStructExt, FieldsNamedAppend}; use quote::quote; use syn::{AttributeArgs, DeriveInput, Fields, FieldsNamed, parse_macro_input, parse_quote, Type}; mod db_meta; mod cr; #[proc_macro_attribute] pub fn db_append_shared(args: TokenStream, input: TokenStream) -> TokenStream { let mut ast = parse_macro_input!(input as DeriveInput); let args = parse_macro_input!(args as AttributeArgs); let fields_additional: FieldsNamed = parse_quote!({ #[serde(default)] pub id: String, #[serde(default)] pub create_time: i64, #[serde(default)] pub update_time: i64, }); ast.a
n.into() } #[proc_macro_derive(DbBeforeUpdate)] pub fn db_before_update(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let name = &ast.ident; let gen = quote! { impl dao::BeforeUpdate for #name { fn before_update(&mut self){ self.set_update_time(kits::now_ts_seconds()); } } }; if cfg!(feature = "print_macro") { println!("\n............gen impl DbBeforeUpdate {}:\n {}", name, gen); } gen.into() } #[proc_macro_derive(DlStruct)] pub fn dl_struct(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let name = &ast.ident; let mut drops = Vec::new(); for field in ast.fields().iter() { if let (Type::Ptr(_), Some(ident)) = (&field.ty, field.ident.as_ref()) { let fname = ident; drops.push(quote! { self.#fname.free(); }); } } let gen = TokenStream::from(quote! { impl CStruct for #name { fn free(&mut self) { #(#drops)* } } impl Drop for #name { fn drop(&mut self) { self.free(); } } }); if cfg!(feature = "print_macro") { println!("\n............gen impl dl_struct {}:\n {}", name, gen); } gen } #[proc_macro_derive(DlDefault)] pub fn dl_default(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let name = &ast.ident; let mut drops = Vec::new(); for field in ast.fields().iter() { if let Some(ident) = field.ident.as_ref() { let fname = ident; if let Type::Ptr(_) = &field.ty { drops.push(quote! { #fname : std::ptr::null_mut() }); } else { drops.push(quote! { #fname : Default::default() }); } } } let gen = TokenStream::from(quote! { impl Default for #name { fn default() -> Self { #name { #(#drops,)* } } } }); if cfg!(feature = "print_macro") { println!("............gen impl dl_default {}:\n {}", name, gen); } gen } #[proc_macro_derive(DlCR)] pub fn dl_cr(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); cr::dl_cr(&ast.ident.to_string(), &ast.fields()) } #[proc_macro_derive(DlDrop)] pub fn dl_drop(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let name = &ast.ident; let gen = TokenStream::from(quote! { impl Drop for #name { fn drop(&mut self) { self.free(); } } }); if cfg!(feature = "print_macro") { println!("............gen impl dl_drop {}:\n {}", name, gen); } gen } pub(crate) fn to_snake_name(name: &String) -> String { let chs = name.chars(); let mut new_name = String::new(); let mut index = 0; let chs_len = name.len(); for x in chs { if x.is_uppercase() { if index != 0 && (index + 1) != chs_len { new_name.push_str("_"); } new_name.push_str(x.to_lowercase().to_string().as_str()); } else { new_name.push(x); } index += 1; } return new_name; } #[cfg(test)] mod tests { use syn::{Fields, FieldsNamed, parse_quote, Type}; #[test] fn it_works() { let fields_named: FieldsNamed = parse_quote! {{ pub id: *mut c_char, pub count: u32, pub name: *mut c_char, pub next: *mut Dl, }}; let fields = Fields::from(fields_named); let mut count = 0; for field in fields.iter() { if let Type::Ptr(_) = field.ty { count += 1; println!("\nttt: {}, {}", field.ident.as_ref().unwrap().to_string(), "raw ptr"); } } assert_eq!(3, count); } }
ppend_named(fields_additional); let name = &ast.ident; let imp_base = quote! { impl Shared for #name { fn get_id(&self) -> String { self.id.clone() } fn set_id(&mut self, id: String) { self.id = id; } fn get_create_time(&self) -> i64 { self.create_time } fn set_create_time(&mut self, create_time: i64) { self.create_time = create_time; } fn get_update_time(&self) -> i64 { self.update_time } fn set_update_time(&mut self, update_time: i64) { self.update_time = update_time; } } }; let impl_crud = if args.is_empty() { quote! {} } else { quote! { impl CRUDTable for #name { type IdType = String; fn get_id(&self) -> Option<&Self::IdType>{ if self.id.is_empty() { None }else{ Some(&self.id) } } } } }; let fields_stream = db_field_name(&ast.ident, &ast.fields()); let gen = TokenStream::from(quote! { #ast #fields_stream #imp_base #impl_crud }); if cfg!(feature = "print_macro") { println!("\n............gen impl db_append_shared {}:\n {}", name, gen); } if cfg!(feature = "db_meta") { let mut meta = db_meta::DbMeta::get().lock().expect("db_meta::DbMeta::get().lock()"); (*meta).push(&ast); } gen } #[proc_macro_attribute] pub fn db_sub_struct(_: TokenStream, input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let fields_stream = db_field_name(&ast.ident, &ast.fields()); let gen = TokenStream::from(quote! { #ast #fields_stream }); if cfg!(feature = "print_macro") { println!("\n////// gen impl db_sub_struct {}:\n {}", &ast.ident.to_string(), gen); } if cfg!(feature = "db_meta") { let mut meta = db_meta::DbMeta::get().lock().expect("db_meta::DbMeta::get().lock()"); (*meta).push_sub_struct(&ast); } gen } fn db_field_name(name: &syn::Ident, fields: &Fields) -> proc_macro2::TokenStream { let fields_stream = { let mut fields_vec = Vec::new(); for f in fields { let field_ident = &f.ident; if let Some(id) = &f.ident { let field_name = id.to_string(); fields_vec.push(quote! {pub const #field_ident : &'a str = #field_name; }); } } if fields_vec.is_empty() { quote! {} } else { quote! { #[allow(non_upper_case_globals)] impl<'a> #name { #(#fields_vec)* } } } }; fields_stream } #[proc_macro_derive(DbBeforeSave)] pub fn db_before_save(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let name = &ast.ident; let gen = quote! { impl dao::BeforeSave for #name { fn before_save(&mut self){ if Shared::get_id(self).is_empty() { self.set_id(kits::uuid()); self.set_update_time(kits::now_ts_seconds()); self.set_create_time(self.get_update_time()); } else { self.set_update_time(kits::now_ts_seconds()); } } } }; if cfg!(feature = "print_macro") { println!("\n............gen impl DbBeforeSave {}:\n {}", name, gen); } ge
random
[ { "content": "pub fn dl_cr(type_name: &str, fields: &Fields) -> TokenStream {\n\n const NAME: &str = \"\";//CExtrinsicContext,CInitParameters\n\n let r_name = {\n\n let mut str = type_name.to_owned();\n\n str.remove(0);\n\n format_ident!(\"{}\",str)\n\n };\n\n //test\n\n if t...
Rust
crates/shim/src/synchronous/mod.rs
QuarkContainer/rust-extensions
b3ac82d9cc2a2674543118bb282537d132870c1a
/* Copyright The containerd Authors. 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::env; use std::fs; use std::io::Write; use std::os::unix::fs::FileTypeExt; use std::os::unix::io::AsRawFd; use std::path::Path; use std::process::{self, Command, Stdio}; use std::sync::{Arc, Condvar, Mutex}; use command_fds::{CommandFdExt, FdMapping}; use libc::{c_int, pid_t, SIGCHLD, SIGINT, SIGPIPE, SIGTERM}; pub use log::{debug, error, info, warn}; use signal_hook::iterator::Signals; use crate::protos::protobuf::Message; use crate::protos::shim::shim_ttrpc::{create_task, Task}; use crate::protos::ttrpc::{Client, Server}; use util::{read_address, write_address}; use crate::api::DeleteResponse; use crate::synchronous::publisher::RemotePublisher; use crate::Error; use crate::{args, logger, reap, Result, TTRPC_ADDRESS}; use crate::{parse_sockaddr, socket_address, start_listener, Config, StartOpts, SOCKET_FD}; pub mod monitor; pub mod publisher; pub mod util; pub mod console; #[allow(clippy::mutex_atomic)] #[derive(Default)] pub struct ExitSignal(Mutex<bool>, Condvar); #[allow(clippy::mutex_atomic)] impl ExitSignal { pub fn signal(&self) { let (lock, cvar) = (&self.0, &self.1); let mut exit = lock.lock().unwrap(); *exit = true; cvar.notify_all(); } pub fn wait(&self) { let (lock, cvar) = (&self.0, &self.1); let mut started = lock.lock().unwrap(); while !*started { started = cvar.wait(started).unwrap(); } } } pub trait Shim { type T: Task + Send + Sync; fn new(runtime_id: &str, id: &str, namespace: &str, config: &mut Config) -> Self; fn start_shim(&mut self, opts: StartOpts) -> Result<String>; fn delete_shim(&mut self) -> Result<DeleteResponse>; fn wait(&mut self); fn create_task_service(&self, publisher: RemotePublisher) -> Self::T; } pub fn run<T>(runtime_id: &str, opts: Option<Config>) where T: Shim + Send + Sync + 'static, { if let Some(err) = bootstrap::<T>(runtime_id, opts).err() { eprintln!("{}: {:?}", runtime_id, err); process::exit(1); } } fn bootstrap<T>(runtime_id: &str, opts: Option<Config>) -> Result<()> where T: Shim + Send + Sync + 'static, { let os_args: Vec<_> = env::args_os().collect(); let flags = args::parse(&os_args[1..])?; let ttrpc_address = env::var(TTRPC_ADDRESS)?; let mut config = opts.unwrap_or_else(Config::default); let signals = setup_signals(&config); if !config.no_sub_reaper { reap::set_subreaper()?; } let mut shim = T::new(runtime_id, &flags.id, &flags.namespace, &mut config); match flags.action.as_str() { "start" => { let args = StartOpts { id: flags.id, publish_binary: flags.publish_binary, address: flags.address, ttrpc_address, namespace: flags.namespace, debug: flags.debug, }; let address = shim.start_shim(args)?; std::io::stdout() .lock() .write_fmt(format_args!("{}", address)) .map_err(io_error!(e, "write stdout"))?; Ok(()) } "delete" => { std::thread::spawn(move || handle_signals(signals)); let response = shim.delete_shim()?; let stdout = std::io::stdout(); let mut locked = stdout.lock(); response.write_to_writer(&mut locked)?; Ok(()) } _ => { if !config.no_setup_logger { logger::init(flags.debug)?; } let publisher = publisher::RemotePublisher::new(&ttrpc_address)?; let task = shim.create_task_service(publisher); let task_service = create_task(Arc::new(Box::new(task))); let mut server = Server::new().register_service(task_service); server = server.add_listener(SOCKET_FD)?; server.start()?; info!("Shim successfully started, waiting for exit signal..."); std::thread::spawn(move || handle_signals(signals)); shim.wait(); info!("Shutting down shim instance"); server.shutdown(); let address = read_address()?; remove_socket_silently(&address); Ok(()) } } } fn setup_signals(config: &Config) -> Signals { let signals = Signals::new(&[SIGTERM, SIGINT, SIGPIPE]).expect("new signal failed"); if !config.no_reaper { signals.add_signal(SIGCHLD).expect("add signal failed"); } signals } fn handle_signals(mut signals: Signals) { loop { for sig in signals.wait() { match sig { SIGTERM | SIGINT => { debug!("received {}", sig); return; } SIGCHLD => loop { unsafe { let pid: pid_t = -1; let mut status: c_int = 0; let options: c_int = libc::WNOHANG; let res_pid = libc::waitpid(pid, &mut status, options); let status = libc::WEXITSTATUS(status); if res_pid <= 0 { break; } else { monitor::monitor_notify_by_pid(res_pid, status).unwrap_or_else(|e| { error!("failed to send exit event {}", e); }); } } }, _ => { debug!("received {}", sig); } } } } } fn wait_socket_working(address: &str, interval_in_ms: u64, count: u32) -> Result<()> { for _i in 0..count { match Client::connect(address) { Ok(_) => { return Ok(()); } Err(_) => { std::thread::sleep(std::time::Duration::from_millis(interval_in_ms)); } } } Err(other!("time out waiting for socket {}", address)) } fn remove_socket_silently(address: &str) { remove_socket(address).unwrap_or_else(|e| warn!("failed to remove file {} {:?}", address, e)) } fn remove_socket(address: &str) -> Result<()> { let path = parse_sockaddr(address); if let Ok(md) = Path::new(path).metadata() { if md.file_type().is_socket() { fs::remove_file(path).map_err(io_error!(e, "remove socket"))?; } } Ok(()) } pub fn spawn(opts: StartOpts, grouping: &str, vars: Vec<(&str, &str)>) -> Result<(u32, String)> { let cmd = env::current_exe().map_err(io_error!(e, ""))?; let cwd = env::current_dir().map_err(io_error!(e, ""))?; let address = socket_address(&opts.address, &opts.namespace, grouping); let listener = match start_listener(&address) { Ok(l) => l, Err(e) => { if e.kind() != std::io::ErrorKind::AddrInUse { return Err(Error::IoError { context: "".to_string(), err: e, }); }; if let Ok(()) = wait_socket_working(&address, 5, 200) { write_address(&address)?; return Ok((0, address)); } remove_socket(&address)?; start_listener(&address).map_err(io_error!(e, ""))? } }; let mut command = Command::new(cmd); command .current_dir(cwd) .stdout(Stdio::null()) .stdin(Stdio::null()) .stderr(Stdio::null()) .fd_mappings(vec![FdMapping { parent_fd: listener.as_raw_fd(), child_fd: SOCKET_FD, }])? .args(&[ "-namespace", &opts.namespace, "-id", &opts.id, "-address", &opts.address, ]); if opts.debug { command.arg("-debug"); } command.envs(vars); command .spawn() .map_err(io_error!(e, "spawn shim")) .map(|child| { std::mem::forget(listener); (child.id(), address) }) } #[cfg(test)] mod tests { use std::thread; use super::*; #[test] fn exit_signal() { let signal = Arc::new(ExitSignal::default()); let cloned = Arc::clone(&signal); let handle = thread::spawn(move || { cloned.signal(); }); signal.wait(); if let Err(err) = handle.join() { panic!("{:?}", err); } } }
/* Copyright The containerd Authors. 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::env; use std::fs; use std::io::Write; use std::os::unix::fs::FileTypeExt; use std::os::unix::io::AsRawFd; use std::path::Path; use std::process::{self, Command, Stdio}; use std::sync::{Arc, Condvar, Mutex}; use command_fds::{CommandFdExt, FdMapping}; use libc::{c_int, pid_t, SIGCHLD, SIGINT, SIGPIPE, SIGTERM}; pub use log::{debug, error, info, warn}; use signal_hook::iterator::Signals; use crate::protos::protobuf::Message; use crate::protos::shim::shim_ttrpc::{create_task, Task}; use crate::protos::ttrpc::{Client, Server}; use util::{read_address, write_address}; use crate::api::DeleteResponse; use crate::synchronous::publisher::RemotePublisher; use crate::Error; use crate::{args, logger, reap, Result, TTRPC_ADDRESS}; use crate::{parse_sockaddr, socket_address, start_listener, Config, StartOpts, SOCKET_FD}; pub mod monitor; pub mod publisher; pub mod util; pub mod console; #[allow(clippy::mutex_atomic)] #[derive(Default)] pub struct ExitSignal(Mutex<bool>, Condvar); #[allow(clippy::mutex_atomic)] impl ExitSignal { pub fn signal(&self) { let (lock, cvar) = (&self.0, &self.1); let mut exit = lock.lock().unwrap(); *exit = true; cvar.notify_all(); } pub fn wait(&self) { let (lock, cvar) = (&self.0, &self.1); let mut started = lock.lock().unwrap(); while !*started { started = cvar.wait(started).unwrap(); } } } pub trait Shim { type T: Task + Send + Sync; fn new(runtime_id: &str, id: &str, namespace: &str, config: &mut Config) -> Self; fn start_shim(&mut self, opts: StartOpts) -> Result<String>; fn delete_shim(&mut self) -> Result<DeleteResponse>; fn wait(&mut self); fn create_task_service(&self, publisher: RemotePublisher) -> Self::T; } pub fn run<T>(runtime_id: &str, opts: Option<Config>) where T: Shim + Send + Sync + 'static, { if let Some(err) = bootstrap::<T>(runtime_id, opts).err() { eprintln!("{}: {:?}", runtime_id, err); process::exit(1); } } fn bootstrap<T>(runtime_id: &str, opts: Option<Config>) -> Result<()> where T: Shim + Send + Sync + 'static, { let os_args: Vec<_> = env::args_os().collect(); let flags = args::parse(&os_args[1..])?; let ttrpc_address = env::var(TTRPC_ADDRESS)?; let mut config = opts.unwrap_or_else(Config::default); let signals = setup_signals(&config); if !config.no_sub_reaper { reap::set_subreaper()?; } let mut shim = T::new(runtime_id, &flags.id, &flags.namespace, &mut config); match flags.action.as_str() { "start" => { let args = StartOpts { id: flags.id, publish_binary: flags.publish_binary, address: flags.address, ttrpc_address, namespace: flags.namespace, debug: flags.debug, }; let address = shim.start_shim(args)?; std::io::stdout() .lock() .write_fmt(format_args!("{}", address)) .map_err(io_error!(e, "write stdout"))?; Ok(()) } "delete" => { std::thread::spawn(move || handle_signals(signals)); let response = shim.delete_shim()?; let stdout = std::io::stdout(); let mut locked = stdout.lock(); response.write_to_writer(&mut locked)?; Ok(()) } _ => { if !config.no_setup_logger { logger::init(flags.debug)?; } let publisher = publisher::RemotePublisher::new(&ttrpc_address)?; let task = shim.create_task_service(publisher); let task_service = create_task(Arc::new(Box::new(task))); let mut server = Server::new().register_service(task_service); server = server.add_listener(SOCKET_FD)?; server.start()?; info!("Shim successfully started, waiting for exit signal..."); std::thread::spawn(move || handle_signals(signals)); shim.wait(); info!("Shutting down shim instance"); server.shutdown(); let address = read_address()?; remove_socket_silently(&address); Ok(()) } } } fn setup_signals(config: &Config) -> Signals { let signals = Signals::new(&[SIGTERM, SIGINT, SIGPIPE]).expect("new signal failed"); if !config.no_reaper { signals.add_signal(SIGCHLD).expect("add signal failed"); } signals } fn handle_signals(mut signals: Signals) { loop { for sig in signals.wait() { match sig { SIGTERM | SIGINT => { debug!("received {}", sig); return; } SIGCHLD => loop { unsafe { let pid: pid_t = -1; let mut status: c_int = 0; let options: c_int = libc::WNOHANG; let res_pid = libc::waitpid(pid, &mut status, options); let status = libc::WEXITSTATUS(status); if res_pid <= 0 { break; } else { monitor::monitor_notify_by_pid(res_pid, status).unwrap_or_else(|e| { error!("failed to send exit event {}", e); }); } } }, _ => { debug!("received {}", sig); } } } } } fn wait_socket_working(address: &str, interval_in_ms: u64, count: u32) -> Result<()> { for _i in 0..count { match Client::connect(address) { Ok(_) => { return Ok(()); } Err(_) => { std::thread::sleep(std::time::Duration::from_millis(interval_in_ms)); } } } Err(other!("time out waiting for socket {}", address)) } fn remove_socket_silently(address: &str) { remove_socket(address).unwrap_or_else(|e| warn!("failed to remove file {} {:?}", address, e)) } fn remove_socket(address: &str) -> Result<()> { let path = parse_sockaddr(address); if let Ok(md) = Path::new(path).metadata() { if md.file_type().is_socket() { fs::remove_file(path).map_err(io_error!(e, "remove socket"))?; } } Ok(()) } pub fn spawn(opts: StartOpts, grouping: &str, vars: Vec<(&str, &str)>) -> Result<(u32, String)> { let cmd = env::current_exe().map_err(io_error!(e, ""))?; let cwd = env::current_dir().map_err(io_error!(e, ""))?; let address = socket_address(&opts.address, &opts.namespace, grouping); let listener = match start_listener(&address) { Ok(l) => l, Err(e) => { if e.kind() != std::io::ErrorKind::AddrInUse { return Err(Error::IoError { context: "".to_string(), err: e, }); }; if let Ok(()) = wait_socket_working(&address, 5, 200) { write_address(&address)?; return Ok((0, address)); } remove_socket(&address)?; start_listener(&address).map_err(io_error!(e, ""))? } }; let mut command = Command::new(cmd); command .current_dir(cwd)
.args(&[ "-namespace", &opts.namespace, "-id", &opts.id, "-address", &opts.address, ]); if opts.debug { command.arg("-debug"); } command.envs(vars); command .spawn() .map_err(io_error!(e, "spawn shim")) .map(|child| { std::mem::forget(listener); (child.id(), address) }) } #[cfg(test)] mod tests { use std::thread; use super::*; #[test] fn exit_signal() { let signal = Arc::new(ExitSignal::default()); let cloned = Arc::clone(&signal); let handle = thread::spawn(move || { cloned.signal(); }); signal.wait(); if let Err(err) = handle.join() { panic!("{:?}", err); } } }
.stdout(Stdio::null()) .stdin(Stdio::null()) .stderr(Stdio::null()) .fd_mappings(vec![FdMapping { parent_fd: listener.as_raw_fd(), child_fd: SOCKET_FD, }])?
function_block-random_span
[ { "content": "/// Make socket path from containerd socket path, namespace and id.\n\npub fn socket_address(socket_path: &str, namespace: &str, id: &str) -> String {\n\n let path = PathBuf::from(socket_path)\n\n .join(namespace)\n\n .join(id)\n\n .display()\n\n .to_string();\n\n\n\...
Rust
src/linux.rs
TomBebbington/reminisce
1dd6c5516cc7ca5831bfe9bb140a1f807f876576
use libc::{c_char, c_ulong, c_int, c_uint, O_RDONLY, O_NONBLOCK, read}; use inotify::INotify; use inotify::ffi; use glob::glob; use std::borrow::Cow; use std::ffi::{CStr, CString}; use std::io::Error; use std::mem; use std::path::Path; use std::str::FromStr; use {Backend, Event, Joystick}; const JSIOCGAXES: c_uint = 2147576337; const JSIOCGBUTTONS: c_uint = 2147576338; const JSIOCGID: c_uint = 2151705107; const JSIOCGID_LEN: usize = 64; extern { fn open(path: *const c_char, oflag: c_int) -> c_int; fn close(fd: c_int) -> c_int; fn ioctl(fd: c_uint, op: c_uint, result: *mut c_char); } pub struct Native { joysticks: Vec<NativeJoystick>, pending: Vec<Event>, inotify: INotify } impl Native { fn inner_poll(&mut self) -> Option<Event> { self.inotify.available_events().unwrap().iter() .find(|e| (e.is_create() || e.is_delete()) && e.name.starts_with("js")) .map(|e| { let index = FromStr::from_str(&e.name[2..]).unwrap(); if e.is_create() { Event::Connected(index) } else { Event::Disconnected(index) } }) .or_else(|| self.pending.pop().or_else(|| self.joysticks.iter_mut().flat_map(|js| js.poll()).next() ) ) } } impl Drop for Native { fn drop(&mut self) { let mut fresh = unsafe { mem::uninitialized() }; mem::swap(&mut self.inotify, &mut fresh); fresh.close().unwrap(); } } impl Backend for Native { type Joystick = NativeJoystick; fn new() -> Native { let mut joysticks = Vec::with_capacity(4); for entry in glob("/dev/input/js*").unwrap() { if let Ok(path) = entry { if let Some(name) = path.file_name() { if let Some(name) = name.to_str() { if name.starts_with("js") { if let Ok(index) = name[2..].parse() { if let Ok(js) = Joystick::open(index) { joysticks.push(js) } } } } } } } let pending = joysticks.iter().by_ref().map(|js:&NativeJoystick| Event::Connected(js.index)).collect(); let inotify = INotify::init().unwrap(); inotify.add_watch(Path::new("/dev/input"), ffi::IN_CREATE | ffi::IN_DELETE).unwrap(); Native { joysticks: joysticks, pending: pending, inotify: inotify } } fn num_joysticks(&self) -> usize { return self.joysticks.len(); } fn joysticks(&self) -> &[NativeJoystick] { return &self.joysticks; } fn poll(&mut self) -> Option<Event> { match self.inner_poll() { Some(Event::Connected(index)) => { if let Ok(joystick) = NativeJoystick::open(index) { self.joysticks.push(joystick); Some(Event::Connected(index)) } else { self.inner_poll() } }, Some(Event::Disconnected(index)) => { let (arr_index, _) = self.joysticks.iter().map(Joystick::index).enumerate().find(|&(_, i)| i == index).unwrap(); self.joysticks.remove(arr_index); Some(Event::Disconnected(arr_index as u8)) }, v => v } } } pub struct NativeJoystick { index: u8, fd: c_int } impl NativeJoystick { fn poll(&mut self) -> Option<Event> { unsafe { let mut event:LinuxEvent = mem::uninitialized(); loop { let event_size = mem::size_of::<LinuxEvent>() as c_ulong; if read(self.fd, mem::transmute(&mut event), event_size as usize) == -1 { let err = Error::last_os_error(); match Error::last_os_error().raw_os_error().expect("Bad OS Error") { 11 => (), 19 => return Some(Event::Disconnected(self.index)), _ => panic!("{}", err) } } else if event._type & 0x80 == 0 { return Some(match (event._type, event.value) { (1, 0) => Event::ButtonReleased(self.index, event.number), (1, 1) => Event::ButtonPressed(self.index, event.number), (2, _) => Event::AxisMoved(self.index, event.number, event.value as f32 / ::MAX_AXIS_VALUE as f32), _ => panic!("Bad type and value {} {} for joystick", event._type, event.value) }) } } } } } impl ::Joystick for NativeJoystick { type OpenError = Error; fn open(index: u8) -> Result<NativeJoystick, Error> { let path = format!("/dev/input/js{}", index); unsafe { let c_path = CString::new(path.as_bytes()).unwrap(); let fd = open(c_path.as_ptr(), O_RDONLY | O_NONBLOCK); if fd == -1 { Err(Error::last_os_error()) } else { Ok(NativeJoystick { index: index, fd: fd }) } } } fn connected(&self) -> bool { true } fn num_hats(&self) -> u8 { 0 } fn num_axes(&self) -> u8 { unsafe { let mut num_axes: c_char = mem::uninitialized(); ioctl(self.fd as u32, JSIOCGAXES, &mut num_axes as *mut i8); num_axes as u8 } } fn num_buttons(&self) -> u8 { unsafe { let mut num_buttons: c_char = mem::uninitialized(); ioctl(self.fd as u32, JSIOCGBUTTONS, &mut num_buttons as *mut i8); num_buttons as u8 } } fn id(&self) -> Cow<str> { unsafe { let text = String::with_capacity(JSIOCGID_LEN); ioctl(self.fd as u32, JSIOCGID, text.as_ptr() as *mut i8); let mut new_text = String::from_raw_parts(text.as_ptr() as *mut u8, JSIOCGID_LEN, JSIOCGID_LEN); let length = CStr::from_ptr(text.as_ptr() as *const i8).to_bytes().len(); mem::forget(text); new_text.truncate(length); new_text.shrink_to_fit(); new_text.into() } } fn index(&self) -> u8 { self.index } fn battery(&self) -> Option<f32> { None } } impl Drop for NativeJoystick { fn drop(&mut self) { unsafe { if close(self.fd) == -1 { let error = Error::last_os_error(); panic!("Failed to close joystick {} due to {}", self.index, error) } } } } #[repr(C)] pub struct LinuxEvent { time: u32, value: i16, _type: u8, number: u8 }
use libc::{c_char, c_ulong, c_int, c_uint, O_RDONLY, O_NONBLOCK, read}; use inotify::INotify; use inotify::ffi; use glob::glob; use std::borrow::Cow; use std::ffi::{CStr, CString}; use std::io::Error; use std::mem; use std::path::Path; use std::str::FromStr; use {Backend, Event, Joystick}; const JSIOCGAXES: c_uint = 2147576337; const JSIOCGBUTTONS: c_uint = 2147576338; const JSIOCGID: c_uint = 2151705107; const JSIOCGID_LEN: usize = 64; extern { fn open(path: *const c_char, oflag: c_int) -> c_int; fn close(fd: c_int) -> c_int; fn ioctl(fd: c_uint, op: c_uint, result: *mut c_char); } pub struct Native { joysticks: Vec<NativeJoystick>, pending: Vec<Event>, inotify: INotify } impl Native { fn inner_poll(&mut self) -> Option<Event> { self.inotify.available_events().unwrap().iter() .find(|e| (e.is_create() || e.is_delete()) && e.name.starts_with("js")) .map(|e| { let index = FromStr::from_str(&e.name[2..]).unwrap(); if e.is_create() { Event::Connected(index) } else { Event::Disconnected(index) } }) .or_else(|| self.pending.pop().or_else(|| self.joysticks.iter_mut().flat_map(|js| js.poll()).next() ) ) } } impl Drop for Native { fn drop(&mut self) { let mut fresh = unsafe { mem::uninitialized() }; mem::swap(&mut self.inotify, &mut fresh); fresh.close().unwrap(); } } impl Backend for Native { type Joystick = NativeJoystick; fn new() -> Native { let mut joysticks = Vec::with_capacity(4); for entry in glob("/dev/input/js*").unwrap() { if let Ok(path) = entry { if let Some(name) = path.file_name() { if let Some(name) = name.to_str() { if name.starts_with("js") { if let Ok(index) = name[2..].parse() { if let Ok(js) = Joystick::open(index) { joysticks.push(js) } } } } } } } let pending = joysticks.iter().by_ref().map(|js:&NativeJoystick| Event::Connected(js.index)).collect(); let inotify = INotify::init().unwrap(); inotify.add_watch(Path::new("/dev/input"), ffi::IN_CREATE | ffi::IN_DELETE).unwrap(); Native { joysticks: joysticks, pending: pending, inotify: inotify } } fn num_joysticks(&self) -> usize { return self.joysticks.len(); } fn joysticks(&self) -> &[NativeJoystick] { return &self.joysticks; } fn poll(&mut self) -> Option<Event> {
} } pub struct NativeJoystick { index: u8, fd: c_int } impl NativeJoystick { fn poll(&mut self) -> Option<Event> { unsafe { let mut event:LinuxEvent = mem::uninitialized(); loop { let event_size = mem::size_of::<LinuxEvent>() as c_ulong; if read(self.fd, mem::transmute(&mut event), event_size as usize) == -1 { let err = Error::last_os_error(); match Error::last_os_error().raw_os_error().expect("Bad OS Error") { 11 => (), 19 => return Some(Event::Disconnected(self.index)), _ => panic!("{}", err) } } else if event._type & 0x80 == 0 { return Some(match (event._type, event.value) { (1, 0) => Event::ButtonReleased(self.index, event.number), (1, 1) => Event::ButtonPressed(self.index, event.number), (2, _) => Event::AxisMoved(self.index, event.number, event.value as f32 / ::MAX_AXIS_VALUE as f32), _ => panic!("Bad type and value {} {} for joystick", event._type, event.value) }) } } } } } impl ::Joystick for NativeJoystick { type OpenError = Error; fn open(index: u8) -> Result<NativeJoystick, Error> { let path = format!("/dev/input/js{}", index); unsafe { let c_path = CString::new(path.as_bytes()).unwrap(); let fd = open(c_path.as_ptr(), O_RDONLY | O_NONBLOCK); if fd == -1 { Err(Error::last_os_error()) } else { Ok(NativeJoystick { index: index, fd: fd }) } } } fn connected(&self) -> bool { true } fn num_hats(&self) -> u8 { 0 } fn num_axes(&self) -> u8 { unsafe { let mut num_axes: c_char = mem::uninitialized(); ioctl(self.fd as u32, JSIOCGAXES, &mut num_axes as *mut i8); num_axes as u8 } } fn num_buttons(&self) -> u8 { unsafe { let mut num_buttons: c_char = mem::uninitialized(); ioctl(self.fd as u32, JSIOCGBUTTONS, &mut num_buttons as *mut i8); num_buttons as u8 } } fn id(&self) -> Cow<str> { unsafe { let text = String::with_capacity(JSIOCGID_LEN); ioctl(self.fd as u32, JSIOCGID, text.as_ptr() as *mut i8); let mut new_text = String::from_raw_parts(text.as_ptr() as *mut u8, JSIOCGID_LEN, JSIOCGID_LEN); let length = CStr::from_ptr(text.as_ptr() as *const i8).to_bytes().len(); mem::forget(text); new_text.truncate(length); new_text.shrink_to_fit(); new_text.into() } } fn index(&self) -> u8 { self.index } fn battery(&self) -> Option<f32> { None } } impl Drop for NativeJoystick { fn drop(&mut self) { unsafe { if close(self.fd) == -1 { let error = Error::last_os_error(); panic!("Failed to close joystick {} due to {}", self.index, error) } } } } #[repr(C)] pub struct LinuxEvent { time: u32, value: i16, _type: u8, number: u8 }
match self.inner_poll() { Some(Event::Connected(index)) => { if let Ok(joystick) = NativeJoystick::open(index) { self.joysticks.push(joystick); Some(Event::Connected(index)) } else { self.inner_poll() } }, Some(Event::Disconnected(index)) => { let (arr_index, _) = self.joysticks.iter().map(Joystick::index).enumerate().find(|&(_, i)| i == index).unwrap(); self.joysticks.remove(arr_index); Some(Event::Disconnected(arr_index as u8)) }, v => v }
if_condition
[ { "content": "/// Scan for joysticks\n\npub fn scan() -> Vec<NativeJoystick> {\n\n\t(0..4).filter_map(|i| ::Joystick::open(i).ok()).collect()\n\n}\n\n\n\npub struct NativeJoystick {\n\n\tindex: u8,\n\n\tlast: Gamepad,\n\n\tlast_packet: i32,\n\n\tevents: VecDeque<::Event>\n\n}\n\nimpl ::Joystick for NativeJoysti...
Rust
psyche-core/src/brain_builder.rs
PsichiX/psyche
b46a98926eeb103b7e158dbb5bc6b53b369683a8
use crate::brain::Brain; use crate::config::Config; use crate::neuron::{NeuronID, Position}; use crate::Scalar; use rand::{thread_rng, Rng}; use serde::{Deserialize, Serialize}; use std::f64::consts::PI; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct BrainBuilder { config: Config, neurons: usize, connections: usize, radius: Scalar, min_neurogenesis_range: Scalar, max_neurogenesis_range: Scalar, sensors: usize, effectors: usize, no_loop_connections: bool, max_connecting_tries: usize, } impl Default for BrainBuilder { fn default() -> Self { Self { config: Default::default(), neurons: 100, connections: 0, radius: 10.0, min_neurogenesis_range: 0.1, max_neurogenesis_range: 1.0, sensors: 1, effectors: 1, no_loop_connections: true, max_connecting_tries: 10, } } } impl BrainBuilder { pub fn new() -> Self { Self::default() } pub fn config(mut self, config: Config) -> Self { self.config = config; self } pub fn neurons(mut self, value: usize) -> Self { self.neurons = value; self } pub fn connections(mut self, value: usize) -> Self { self.connections = value; self } pub fn radius(mut self, value: Scalar) -> Self { self.radius = value; self } pub fn min_neurogenesis_range(mut self, value: Scalar) -> Self { self.min_neurogenesis_range = value; self } pub fn max_neurogenesis_range(mut self, value: Scalar) -> Self { self.max_neurogenesis_range = value; self } pub fn sensors(mut self, value: usize) -> Self { self.sensors = value; self } pub fn effectors(mut self, value: usize) -> Self { self.effectors = value; self } pub fn no_loop_connections(mut self, value: bool) -> Self { self.no_loop_connections = value; self } pub fn max_connecting_tries(mut self, value: usize) -> Self { self.max_connecting_tries = value; self } pub fn build(mut self) -> Brain { let mut brain = Brain::new(); brain.set_config(self.config.clone()); let mut rng = thread_rng(); let mut neurons = vec![]; neurons.push(brain.create_neuron(Position { x: 0.0, y: 0.0, z: 0.0, })); for _ in 0..self.neurons { neurons.push(self.make_neighbor_neuron(&neurons, &mut brain, &mut rng)); } let neuron_positions = neurons .iter() .map(|id| (*id, brain.neuron(*id).unwrap().position())) .collect::<Vec<_>>(); for _ in 0..self.sensors { let mut tries = self.max_connecting_tries + 1; while tries > 0 && !self.make_peripheral_sensor(&neuron_positions, &mut brain, &mut rng) { tries -= 1; } } for _ in 0..self.effectors { let mut tries = self.max_connecting_tries + 1; while tries > 0 && !self.make_peripheral_effector(&neuron_positions, &mut brain, &mut rng) { tries -= 1; } } for _ in 0..self.connections { let mut tries = self.max_connecting_tries + 1; while tries > 0 && !self.connect_neighbor_neurons(&neuron_positions, &mut brain, &mut rng) { tries -= 1; } } for id in brain.get_neurons() { if !brain.does_neuron_has_connections(id) { drop(brain.kill_neuron(id)); } } brain } fn make_peripheral_sensor<R>( &self, neuron_positions: &[(NeuronID, Position)], brain: &mut Brain, rng: &mut R, ) -> bool where R: Rng, { let pos = self.make_new_peripheral_position(rng); let index = neuron_positions .iter() .map(|(_, p)| p.distance_sqr(pos)) .enumerate() .min_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap()) .unwrap() .0; brain.create_sensor(neuron_positions[index].0).is_ok() } fn make_peripheral_effector<R>( &self, neuron_positions: &[(NeuronID, Position)], brain: &mut Brain, rng: &mut R, ) -> bool where R: Rng, { let pos = self.make_new_peripheral_position(rng); let index = neuron_positions .iter() .map(|(_, p)| p.distance_sqr(pos)) .enumerate() .min_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap()) .unwrap() .0; brain.create_effector(neuron_positions[index].0).is_ok() } fn make_neighbor_neuron<R>( &mut self, neurons: &[NeuronID], brain: &mut Brain, rng: &mut R, ) -> NeuronID where R: Rng, { let distance = rng.gen_range(self.min_neurogenesis_range, self.max_neurogenesis_range); let origin = neurons[rng.gen_range(0, neurons.len()) % neurons.len()]; let origin_pos = brain.neuron(origin).unwrap().position(); let new_position = self.make_new_position(origin_pos, distance, rng); brain.create_neuron(new_position) } fn connect_neighbor_neurons<R>( &mut self, neuron_positions: &[(NeuronID, Position)], brain: &mut Brain, rng: &mut R, ) -> bool where R: Rng, { let origin = neuron_positions[rng.gen_range(0, neuron_positions.len()) % neuron_positions.len()]; let filtered = neuron_positions .iter() .filter_map(|(id, p)| { if p.distance(origin.1) <= self.max_neurogenesis_range { Some(id) } else { None } }) .collect::<Vec<_>>(); let target = *filtered[rng.gen_range(0, filtered.len()) % filtered.len()]; origin.0 != target && (!self.no_loop_connections || (!brain.are_neurons_connected(origin.0, target) && !brain.are_neurons_connected(target, origin.0))) && brain.bind_neurons(origin.0, target).is_ok() } fn make_new_position<R>(&self, pos: Position, scale: Scalar, rng: &mut R) -> Position where R: Rng, { let phi = rng.gen_range(0.0, PI * 2.0); let theta = rng.gen_range(-PI, PI); let pos = Position { x: pos.x + theta.cos() * phi.cos() * scale, y: pos.y + theta.cos() * phi.sin() * scale, z: pos.z + theta.sin() * scale, }; let magnitude = pos.magnitude(); if magnitude > self.radius { Position { x: self.radius * pos.x / magnitude, y: self.radius * pos.y / magnitude, z: self.radius * pos.z / magnitude, } } else { pos } } fn make_new_peripheral_position<R>(&self, rng: &mut R) -> Position where R: Rng, { let phi = rng.gen_range(0.0, PI * 2.0); let theta = rng.gen_range(-PI, PI); Position { x: theta.cos() * phi.cos() * self.radius, y: theta.cos() * phi.sin() * self.radius, z: theta.sin() * self.radius, } } }
use crate::brain::Brain; use crate::config::Config; use crate::neuron::{NeuronID, Position}; use crate::Scalar; use rand::{thread_rng, Rng}; use serde::{Deserialize, Serialize}; use std::f64::consts::PI; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct BrainBuilder { config: Config, neurons: usize, connections: usize, radius: Scalar, min_neurogenesis_range: Scalar, max_neurogenesis_range: Scalar, sensors: usize, effectors: usize, no_loop_connections: bool, max_connecting_tries: usize, } impl Default for BrainBuilder { fn default() -> Self { Self { config: Default::default(), neurons: 100, connections: 0, radius: 10.0, min_neurogenesis_range: 0.1, max_neurogenesis_range: 1.0, sensors: 1, effectors: 1, no_loop_connections: true, max_connecting_tries: 10, } } } impl BrainBuilder { pub fn new() -> Self { Self::default() } pub fn config(mut self, config: Config) -> Self { self.config = config; self } pub fn neurons(mut self, value: usize) -> Self { self.neurons = value; self } pub fn connections(mut self, value: usize) -> Self { self.connections = value; self } pub fn radius(mut self, value: Scalar) -> Self { self.radius = value; self } pub fn min_neurogenesis_range(mut self, value: Scalar) -> Self { self.min_neurogenesis_range = value; self } pub fn max_neurogenesis_range(mut self, value: Scalar) -> Self { self.max_neurogenesis_range = value; self } pub fn sensors(mut self, value: usize) -> Self { self.sensors = value; self } pub fn effectors(mut self, value: usize) -> Self { self.effectors = value; self } pub fn no_loop_connections(mut self, value: bool) -> Self { self.no_loop_connections = value; self } pub fn max_connecting_tries(mut self, value: usize) -> Self { self.max_connecting_tries = value; self } pub fn build(mut self) -> Brain { let mut brain = Brain::new(); brain.set_config(self.config.clone()); let mut rng = thread_rng(); let mut neurons = vec![]; neurons.push(brain.create_neuron(Position { x: 0.0, y: 0.0, z: 0.0, })); for _ in 0..self.neurons { neurons.push(self.make_neighbor_neuron(&neurons, &mut brain, &mut rng)); } let neuron_positions = neurons .iter() .map(|id| (*id, brain.neuron(*id).unwrap().position())) .collect::<Vec<_>>(); for _ in 0..self.sensors { let mut tries = self.max_connecting_tries + 1; while tries > 0 && !self.make_peripheral_sensor(&neuron_positions, &mut brain, &mut rng) { tries -= 1; } } for _ in 0..self.effectors { let mut tries = self.max_connecting_tries + 1; while tries > 0 && !self.make_peripheral_effector(&neuron_positions, &mut brain, &mut rng) { tries -= 1; } } for _ in 0..self.connections { let mut tries = self.max_connecting_tries + 1; while tries > 0 && !self.connect_neighbor_neurons(&neuron_positions, &mut brain, &mut rng) { tries -= 1; } } for id in brain.get_neurons() { if !brain.does_neuron_has_connections(id) { drop(brain.kill_neuron(id)); } } brain } fn make_peripheral_sensor<R>( &self, neuron_positions: &[(NeuronID, Position)], brain: &mut Brain, rng: &mut R, ) -> bool where R: Rng, { let pos = self.make_new_peripheral_position(rng); let index = neuron_positions .iter() .map(|(_, p)| p.distance_sqr(pos)) .enumerate() .min_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap()) .unwrap() .0; brain.create_sensor(neuron_positions[index].0).is_ok() } fn make_peripheral_effector<R>( &self, neuron_positions: &[(NeuronID, Position)], brain: &mut Brain, rng: &mut R, ) -> bool where R: Rng, { let pos = self.make_new_peripheral_position(rng); let index = neuron_positions .iter() .map(|(_, p)| p.distance_sqr(pos)) .enumerate() .min_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap()) .unwrap() .0; brain.create_effector(neuron_positions[index].0).is_ok() }
fn connect_neighbor_neurons<R>( &mut self, neuron_positions: &[(NeuronID, Position)], brain: &mut Brain, rng: &mut R, ) -> bool where R: Rng, { let origin = neuron_positions[rng.gen_range(0, neuron_positions.len()) % neuron_positions.len()]; let filtered = neuron_positions .iter() .filter_map(|(id, p)| { if p.distance(origin.1) <= self.max_neurogenesis_range { Some(id) } else { None } }) .collect::<Vec<_>>(); let target = *filtered[rng.gen_range(0, filtered.len()) % filtered.len()]; origin.0 != target && (!self.no_loop_connections || (!brain.are_neurons_connected(origin.0, target) && !brain.are_neurons_connected(target, origin.0))) && brain.bind_neurons(origin.0, target).is_ok() } fn make_new_position<R>(&self, pos: Position, scale: Scalar, rng: &mut R) -> Position where R: Rng, { let phi = rng.gen_range(0.0, PI * 2.0); let theta = rng.gen_range(-PI, PI); let pos = Position { x: pos.x + theta.cos() * phi.cos() * scale, y: pos.y + theta.cos() * phi.sin() * scale, z: pos.z + theta.sin() * scale, }; let magnitude = pos.magnitude(); if magnitude > self.radius { Position { x: self.radius * pos.x / magnitude, y: self.radius * pos.y / magnitude, z: self.radius * pos.z / magnitude, } } else { pos } } fn make_new_peripheral_position<R>(&self, rng: &mut R) -> Position where R: Rng, { let phi = rng.gen_range(0.0, PI * 2.0); let theta = rng.gen_range(-PI, PI); Position { x: theta.cos() * phi.cos() * self.radius, y: theta.cos() * phi.sin() * self.radius, z: theta.sin() * self.radius, } } }
fn make_neighbor_neuron<R>( &mut self, neurons: &[NeuronID], brain: &mut Brain, rng: &mut R, ) -> NeuronID where R: Rng, { let distance = rng.gen_range(self.min_neurogenesis_range, self.max_neurogenesis_range); let origin = neurons[rng.gen_range(0, neurons.len()) % neurons.len()]; let origin_pos = brain.neuron(origin).unwrap().position(); let new_position = self.make_new_position(origin_pos, distance, rng); brain.create_neuron(new_position) }
function_block-full_function
[ { "content": "/// generates OBJ bytes from activity map.\n\n/// NOTE: Colors are stored either in vertices normals or texture vertices.\n\npub fn generate(activity_map: &BrainActivityMap, config: &Config) -> Result<Vec<u8>> {\n\n let mut objects = vec![];\n\n\n\n if let Some(ref neurons) = config.neurons ...
Rust
tests/embedded_graphics.rs
hpux735/tinybmp
a2bddd0767294e21d66a7c295215121230efb7a8
use embedded_graphics::{ image::Image, mock_display::{ColorMapping, MockDisplay}, pixelcolor::{Gray8, Rgb555, Rgb565, Rgb888}, prelude::*, primitives::Rectangle, }; use tinybmp::{Bmp, DynamicBmp}; #[test] fn negative_top_left() { let image: Bmp<Rgb565> = Bmp::from_slice(include_bytes!("./chessboard-4px-color-16bit.bmp")).unwrap(); let image = Image::new(&image, Point::zero()).translate(Point::new(-1, -1)); assert_eq!( image.bounding_box(), Rectangle::new(Point::new(-1, -1), Size::new(4, 4)) ); } #[test] fn dimensions() { let image: Bmp<Rgb565> = Bmp::from_slice(include_bytes!("./chessboard-4px-color-16bit.bmp")).unwrap(); let image = Image::new(&image, Point::zero()).translate(Point::new(100, 200)); assert_eq!( image.bounding_box(), Rectangle::new(Point::new(100, 200), Size::new(4, 4)) ); } fn expected_image_color<C>() -> MockDisplay<C> where C: PixelColor + ColorMapping, { MockDisplay::from_pattern(&[ "KRGY", "BMCW", ]) } fn expected_image_gray() -> MockDisplay<Gray8> { MockDisplay::from_pattern(&["08F"]) } fn draw_image<C, T>(image_drawable: T) -> MockDisplay<C> where C: PixelColor, T: ImageDrawable<Color = C>, { let image = Image::new(&image_drawable, Point::zero()); let mut display = MockDisplay::new(); image.draw(&mut display).unwrap(); display } fn test_color_pattern<C>(data: &[u8]) where C: PixelColor + From<<C as PixelColor>::Raw> + ColorMapping, { let bmp = Bmp::<C>::from_slice(data).unwrap(); draw_image(bmp).assert_eq(&expected_image_color()); } fn test_color_pattern_dynamic(data: &[u8]) { let bmp = DynamicBmp::from_slice(data).unwrap(); draw_image(bmp).assert_eq(&expected_image_color::<Rgb565>()); let bmp = DynamicBmp::from_slice(data).unwrap(); draw_image(bmp).assert_eq(&expected_image_color::<Rgb888>()); } #[test] fn colors_rgb555() { test_color_pattern::<Rgb555>(include_bytes!("./colors_rgb555.bmp")); } #[test] fn colors_rgb555_dynamic() { test_color_pattern_dynamic(include_bytes!("./colors_rgb555.bmp")); } #[test] fn colors_rgb565() { test_color_pattern::<Rgb565>(include_bytes!("./colors_rgb565.bmp")); } #[test] fn colors_rgb565_dynamic() { test_color_pattern_dynamic(include_bytes!("./colors_rgb565.bmp")); } #[test] fn colors_rgb888_24bit() { test_color_pattern::<Rgb888>(include_bytes!("./colors_rgb888_24bit.bmp")); } #[test] fn colors_rgb888_24bit_dynamic() { test_color_pattern_dynamic(include_bytes!("./colors_rgb888_24bit.bmp")); } #[test] fn colors_rgb888_32bit() { test_color_pattern::<Rgb888>(include_bytes!("./colors_rgb888_32bit.bmp")); } #[test] fn colors_rgb888_32bit_dynamic() { test_color_pattern_dynamic(include_bytes!("./colors_rgb888_32bit.bmp")); } #[test] fn colors_grey8() { let bmp: Bmp<Gray8> = Bmp::from_slice(include_bytes!("./colors_grey8.bmp")).unwrap(); draw_image(bmp).assert_eq(&expected_image_gray()); } #[test] fn colors_grey8_dynamic() { let bmp = DynamicBmp::from_slice(include_bytes!("./colors_grey8.bmp")).unwrap(); let display = draw_image::<Rgb565, _>(bmp); display.assert_eq(&expected_image_gray().map(|c| c.into())); let bmp = DynamicBmp::from_slice(include_bytes!("./colors_grey8.bmp")).unwrap(); let display = draw_image::<Rgb888, _>(bmp); display.assert_eq(&expected_image_gray().map(|c| c.into())); } #[test] fn issue_136_row_size_is_multiple_of_4_bytes() { let image: Bmp<Rgb565> = Bmp::from_slice(include_bytes!("./issue_136.bmp")).unwrap(); let image = Image::new(&image, Point::zero()); let mut display = MockDisplay::new(); image.draw(&mut display).unwrap(); display.assert_pattern(&[ "WWWWKWWWW", "WKKKKWKKK", "WWWWKWKWW", "WKKKKWKKW", "WWWWKWWWW", ]); }
use embedded_graphics::{ image::Image, mock_display::{ColorMapping, MockDisplay}, pixelcolor::{Gray8, Rgb555, Rgb565, Rgb888}, prelude::*, primitives::Rectangle, }; use tinybmp::{Bmp, DynamicBmp}; #[test] fn negative_top_left() { let image: Bmp<Rgb565> = Bmp::from_slice(include_bytes!("./chessboard-4px-color-16bit.bmp")).unwrap(); let image = Image::new(&image, Point::zero()).translate(Point::new(-1, -1)); assert_eq!( image.bounding_box(), Rectangle::new(Point::new(-1, -1), Size::new(4, 4)) ); } #[test] fn dimensions() { let image: Bmp<Rgb565> = Bmp::from_slice(include_bytes!("./chessboard-4px-color-16bit.bmp")).unwrap(); let image = Image::new(&image, Point::zero()).translate(Point::new(100, 200)); assert_eq!( image.bounding_box(), Rectangle::new(Point::new(100, 200), Size::new(4, 4)) ); } fn expected_image_color<C>() -> MockDisplay<C> where C: PixelColor + ColorMapping, { MockDisplay::from_pattern(&[ "KRGY", "BMCW", ]) } fn expected_image_gray() -> MockDisplay<Gray8> { MockDisplay::from_pattern(&["08F"]) } fn draw_image<C, T>(image_drawable: T) -> MockDisplay<C> where C: PixelColor, T: ImageDrawable<Color = C>, { let image = Image::new(&image_drawable, Point::zero()); let mut display = MockDisplay::new(); image.draw(&mut display).unwrap(); display } fn test_color_pattern<C>(data: &[u8]) where C: PixelColor + From<<C as PixelColor>::Raw> + ColorMapping, { let bmp = Bmp::<C>::from_slice(data).unwrap(); draw_image(bmp).assert_eq(&expected_image_color()); } fn test_color_pattern_dynamic(data: &[u8]) { let bmp = DynamicBmp::from_slice(data).unwrap();
#[test] fn colors_rgb555() { test_color_pattern::<Rgb555>(include_bytes!("./colors_rgb555.bmp")); } #[test] fn colors_rgb555_dynamic() { test_color_pattern_dynamic(include_bytes!("./colors_rgb555.bmp")); } #[test] fn colors_rgb565() { test_color_pattern::<Rgb565>(include_bytes!("./colors_rgb565.bmp")); } #[test] fn colors_rgb565_dynamic() { test_color_pattern_dynamic(include_bytes!("./colors_rgb565.bmp")); } #[test] fn colors_rgb888_24bit() { test_color_pattern::<Rgb888>(include_bytes!("./colors_rgb888_24bit.bmp")); } #[test] fn colors_rgb888_24bit_dynamic() { test_color_pattern_dynamic(include_bytes!("./colors_rgb888_24bit.bmp")); } #[test] fn colors_rgb888_32bit() { test_color_pattern::<Rgb888>(include_bytes!("./colors_rgb888_32bit.bmp")); } #[test] fn colors_rgb888_32bit_dynamic() { test_color_pattern_dynamic(include_bytes!("./colors_rgb888_32bit.bmp")); } #[test] fn colors_grey8() { let bmp: Bmp<Gray8> = Bmp::from_slice(include_bytes!("./colors_grey8.bmp")).unwrap(); draw_image(bmp).assert_eq(&expected_image_gray()); } #[test] fn colors_grey8_dynamic() { let bmp = DynamicBmp::from_slice(include_bytes!("./colors_grey8.bmp")).unwrap(); let display = draw_image::<Rgb565, _>(bmp); display.assert_eq(&expected_image_gray().map(|c| c.into())); let bmp = DynamicBmp::from_slice(include_bytes!("./colors_grey8.bmp")).unwrap(); let display = draw_image::<Rgb888, _>(bmp); display.assert_eq(&expected_image_gray().map(|c| c.into())); } #[test] fn issue_136_row_size_is_multiple_of_4_bytes() { let image: Bmp<Rgb565> = Bmp::from_slice(include_bytes!("./issue_136.bmp")).unwrap(); let image = Image::new(&image, Point::zero()); let mut display = MockDisplay::new(); image.draw(&mut display).unwrap(); display.assert_pattern(&[ "WWWWKWWWW", "WKKKKWKKK", "WWWWKWKWW", "WKKKKWKKW", "WWWWKWWWW", ]); }
draw_image(bmp).assert_eq(&expected_image_color::<Rgb565>()); let bmp = DynamicBmp::from_slice(data).unwrap(); draw_image(bmp).assert_eq(&expected_image_color::<Rgb888>()); }
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn coordinates() {\n\n let bmp = RawBmp::from_slice(include_bytes!(\"./chessboard-8px-color-16bit.bmp\"))\n\n .expect(\"Failed to parse\");\n\n\n\n let pixels: Vec<_> = bmp\n\n .pixels()\n\n .map(|pixel| (pixel.position.x, pixel.position.y))\n\n .collec...
Rust
src/io_event.rs
mbrubeck/smol
c311b6897fb7525ef876070d80f6ee375686b605
use std::io::{self, Read, Write}; #[cfg(windows)] use std::net::SocketAddr; use std::sync::atomic::{self, AtomicBool, Ordering}; use std::sync::Arc; #[cfg(not(target_os = "linux"))] use socket2::{Domain, Socket, Type}; use crate::async_io::Async; #[cfg(not(target_os = "linux"))] type Notifier = Socket; #[cfg(target_os = "linux")] type Notifier = linux::EventFd; struct Inner { flag: AtomicBool, writer: Notifier, reader: Async<Notifier>, } #[derive(Clone)] pub(crate) struct IoEvent(Arc<Inner>); impl IoEvent { pub fn new() -> io::Result<IoEvent> { let (writer, reader) = notifier()?; Ok(IoEvent(Arc::new(Inner { flag: AtomicBool::new(false), writer, reader: Async::new(reader)?, }))) } pub fn notify(&self) { atomic::fence(Ordering::SeqCst); if !self.0.flag.load(Ordering::SeqCst) { if !self.0.flag.swap(true, Ordering::SeqCst) { let _ = (&self.0.writer).write(&1u64.to_ne_bytes()); let _ = (&self.0.writer).flush(); let _ = self.0.reader.reregister_io_event(); } } } pub fn clear(&self) -> bool { while self.0.reader.get_ref().read(&mut [0; 64]).is_ok() {} let value = self.0.flag.swap(false, Ordering::SeqCst); atomic::fence(Ordering::SeqCst); value } pub async fn notified(&self) { self.0 .reader .read_with(|_| { if self.0.flag.load(Ordering::SeqCst) { Ok(()) } else { Err(io::ErrorKind::WouldBlock.into()) } }) .await .expect("failure while waiting on a self-pipe"); } } #[cfg(all(unix, not(target_os = "linux")))] fn notifier() -> io::Result<(Socket, Socket)> { let (sock1, sock2) = Socket::pair(Domain::unix(), Type::stream(), None)?; sock1.set_nonblocking(true)?; sock2.set_nonblocking(true)?; sock1.set_send_buffer_size(1)?; sock2.set_recv_buffer_size(1)?; Ok((sock1, sock2)) } #[cfg(target_os = "linux")] mod linux { use super::*; use nix::sys::eventfd::{eventfd, EfdFlags}; use std::os::unix::io::AsRawFd; pub(crate) struct EventFd(std::os::unix::io::RawFd); impl EventFd { pub fn new() -> Result<Self, std::io::Error> { let fd = eventfd(0, EfdFlags::EFD_CLOEXEC | EfdFlags::EFD_NONBLOCK).map_err(io_err)?; Ok(EventFd(fd)) } pub fn try_clone(&self) -> Result<EventFd, io::Error> { nix::unistd::dup(self.0).map(EventFd).map_err(io_err) } } impl AsRawFd for EventFd { fn as_raw_fd(&self) -> i32 { self.0 } } impl Drop for EventFd { fn drop(&mut self) { let _ = nix::unistd::close(self.0); } } fn io_err(err: nix::Error) -> io::Error { match err { nix::Error::Sys(code) => code.into(), err => io::Error::new(io::ErrorKind::Other, Box::new(err)), } } impl Read for &EventFd { #[inline] fn read(&mut self, buf: &mut [u8]) -> std::result::Result<usize, std::io::Error> { nix::unistd::read(self.0, buf).map_err(io_err) } } impl Write for &EventFd { #[inline] fn write(&mut self, buf: &[u8]) -> std::result::Result<usize, std::io::Error> { nix::unistd::write(self.0, buf).map_err(io_err) } #[inline] fn flush(&mut self) -> std::result::Result<(), std::io::Error> { Ok(()) } } } #[cfg(target_os = "linux")] fn notifier() -> io::Result<(Notifier, Notifier)> { use linux::EventFd; let sock1 = EventFd::new()?; let sock2 = sock1.try_clone()?; Ok((sock1, sock2)) } #[cfg(windows)] fn notifier() -> io::Result<(Notifier, Notifier)> { let listener = Socket::new(Domain::ipv4(), Type::stream(), None)?; listener.bind(&SocketAddr::from(([127, 0, 0, 1], 0)).into())?; listener.listen(1)?; let sock1 = Socket::new(Domain::ipv4(), Type::stream(), None)?; sock1.set_nonblocking(true)?; let _ = sock1.set_nodelay(true)?; let _ = sock1.connect(&listener.local_addr()?); let (sock2, _) = listener.accept()?; sock2.set_nonblocking(true)?; let _ = sock2.set_nodelay(true)?; sock1.set_send_buffer_size(1)?; sock2.set_recv_buffer_size(1)?; Ok((sock1, sock2)) }
use std::io::{self, Read, Write}; #[cfg(windows)] use std::net::SocketAddr; use std::sync::atomic::{self, AtomicBool, Ordering}; use std::sync::Arc; #[cfg(not(target_os = "linux"))] use socket2::{Domain, Socket, Type}; use crate::async_io::Async; #[cfg(not(target_os = "linux"))] type Notifier = Socket; #[cfg(target_os = "linux")] type Notifier = linux::EventFd; struct Inner { flag: AtomicBool, writer: Notifier, reader: Async<Notifier>, } #[derive(Clone)] pub(crate) struct IoEvent(Arc<Inner>); impl IoEvent { pub fn new() -> io::Result<IoEvent> { let (writer, reader) = notifier()?; Ok(IoEvent(Arc::new(Inner { flag: AtomicBool::new(false), writer, reader: Async::new(reader)?, }))) } pub fn notify(&self) { atomic::fence(Ordering::SeqCst); if !self.0.flag.load(Ordering::SeqCst) { if !self.0.flag.swap(true, Ordering::SeqCst) { let _ = (&self.0.writer).write(&1u64.to_ne_bytes()); let _ = (&self.0.writer).flush(); let _ = self.0.reader.reregister_io_event(); } } } pub fn clear(&self) -> bool { while self.0.reader.get_ref().read(&mut [0; 64]).is_ok() {} let value = self.0.flag.swap(false, Ordering::SeqCst); atomic::fence(Ordering::SeqCst); value } pub async fn notified(&self) { self.0 .reader .read_with(|_| { if self.0.flag.load(Ordering::SeqCst) { Ok(()) } else { Err(io::ErrorKind::WouldBlock.into()) } }) .await .expect("failure while waiting on a self-pipe"); } } #[cfg(all(unix, not(target_os = "linux")))] fn notifier() -> io::Result<(Socket, Socket)> { let (sock1, sock2) = Socket::pair(Domain::unix(), Type::stream(), None)?; sock1.set_nonblocking(true)?; sock2.set_nonblocking(true)?; sock1.set_send_buffer_size(1)?; sock2.set_recv_buffer_size(1)?; Ok((sock1, sock2)) } #[cfg(target_os = "linux")] mod linux { use super::*; use nix::sys::eventfd::{eventfd, EfdFlags}; use std::os::unix::io::AsRawFd; pub(crate) struct EventFd(std::os::unix::io::RawFd); impl EventFd { pub fn new() -> Result<Self, std::io::Error> { let fd = eventfd(0, EfdFlags::EFD_CLOEXEC | EfdFlags::EFD_NONBLOCK).map_err(io_err)?; Ok(EventFd(fd)) } pub fn try_clone(&self) -> Result<EventFd, io::Error> { nix::unistd::dup(self.0).map(EventFd).map_err(io_err) } } impl AsRawFd for EventFd { fn as_raw_fd(&self) -> i32 { self.0 } } impl Drop for EventFd { fn drop(&mut self) { let _ = nix::unistd::close(self.0); } } fn io_err(err: nix::Error) -> io::Error { match err { nix::Error::Sys(code) => code.into(), err => io::Error::new(io::ErrorKind::Other, Box::new(err)), } } impl Read for &EventFd { #[inline] fn read(&mut self, buf: &mut [u8]) -> std::result::Result<usize, std::io::Error> { nix::unistd::read(self.0, buf).map_err(io_err) } } impl Write for &EventFd { #[inline] fn write(&mut self, buf: &[u8]) -> std::result::Result<usize, std::io::Error> { nix::unistd::write(self.0, buf).map_err(io_err) } #[inline] fn flush(&mut self) -> std::result::Result<(), std::io::Error> { Ok(()) } } } #[cfg(target_os = "linux")] fn notifier() -> io::Result<(Notifier, Notifier)> { use linux::EventFd; let sock1 = EventFd::new()?; let sock2 = sock1.try_clone()?; Ok((sock1, sock2)) } #[cfg(windows)]
fn notifier() -> io::Result<(Notifier, Notifier)> { let listener = Socket::new(Domain::ipv4(), Type::stream(), None)?; listener.bind(&SocketAddr::from(([127, 0, 0, 1], 0)).into())?; listener.listen(1)?; let sock1 = Socket::new(Domain::ipv4(), Type::stream(), None)?; sock1.set_nonblocking(true)?; let _ = sock1.set_nodelay(true)?; let _ = sock1.connect(&listener.local_addr()?); let (sock2, _) = listener.accept()?; sock2.set_nonblocking(true)?; let _ = sock2.set_nodelay(true)?; sock1.set_send_buffer_size(1)?; sock2.set_recv_buffer_size(1)?; Ok((sock1, sock2)) }
function_block-full_function
[ { "content": "/// Creates an async writer that runs on a thread.\n\n///\n\n/// This adapter converts any kind of synchronous writer into an asynchronous writer by running it\n\n/// on the blocking executor and receiving bytes over a pipe.\n\n///\n\n/// **Note:** Don't forget to flush the writer at the end, or s...
Rust
canon_collision_lib/src/command_line.rs
rukai/canon_collision
4adfef24ea9dccce8a7306b9d37a55136f11c4df
use winit_input_helper::{WinitInputHelper, TextChar}; use std::collections::VecDeque; use winit::event::VirtualKeyCode; use treeflection::{Node, NodeRunner, NodeToken}; #[derive(Clone, Default, Serialize, Deserialize, Node)] pub struct CommandLine { history_index: isize, cursor: usize, history: Vec<String>, command: String, output: VecDeque<String>, running: bool, } impl CommandLine { pub fn new() -> Self { Self { history_index: -1, cursor: 0, history: vec!(), command: String::new(), output: VecDeque::new(), running: false, } } pub fn step<T>(&mut self, os_input: &WinitInputHelper, root_node: &mut T) where T: Node { if os_input.key_pressed(VirtualKeyCode::Grave) { self.running = !self.running; return; } if self.running { for text_char in os_input.text() { match text_char { TextChar::Char(new_char) => { let mut new_command = String::new(); let mut hit_cursor = false; for (i, old_char) in self.command.char_indices() { if i == self.cursor { hit_cursor = true; new_command.push(new_char); } new_command.push(old_char); } if !hit_cursor { new_command.push(new_char); } self.command = new_command; self.cursor += 1; } TextChar::Back => { if self.cursor > 0 { self.cursor -= 1; let mut new_command = String::new(); for (i, old_char) in self.command.char_indices() { if i != self.cursor { new_command.push(old_char); } } self.command = new_command; } } } self.history_index = -1; } if os_input.key_pressed(VirtualKeyCode::Return) { { let command = format!("→{}", self.command.trim_end()); self.output_add(command); } let result = match NodeRunner::new(self.command.as_str()) { Ok(runner) => root_node.node_step(runner), Err(msg) => msg }; for line in result.split('\n') { self.output_add(line.to_string()); } self.history.insert(0, self.command.trim_end().to_string()); self.history_index = -1; self.command.clear(); self.cursor = 0; } if os_input.key_pressed(VirtualKeyCode::Home) { self.cursor = 0; } if os_input.key_pressed(VirtualKeyCode::End) { self.cursor = self.command.chars().count(); } if os_input.key_pressed(VirtualKeyCode::Left) && self.cursor > 0 { self.cursor -= 1; } if os_input.key_pressed(VirtualKeyCode::Right) && self.cursor < self.command.chars().count() { self.cursor += 1; } if os_input.key_pressed(VirtualKeyCode::Up) && self.history_index + 1 < self.history.len() as isize { self.history_index += 1; self.command = self.history[self.history_index as usize].clone(); self.cursor = self.command.chars().count(); } if os_input.key_pressed(VirtualKeyCode::Down) { if self.history_index > 0 { self.history_index -= 1; self.command = self.history[self.history_index as usize].clone(); self.cursor = self.command.chars().count(); } else if self.history_index == 0 { self.history_index -= 1; self.command.clear(); self.cursor = 0; } } } } fn output_add(&mut self, line: String) { if self.output.len() >= 100 { self.output.pop_back(); } self.output.push_front(line); } pub fn block(&self) -> bool { self.running } pub fn output(&self) -> Vec<String> { if self.running { let mut command = String::from("→"); let mut hit_cursor = false; for (i, c) in self.command.char_indices() { if i == self.cursor { hit_cursor = true; command.push('■'); } command.push(c); } if !hit_cursor { command.push('■'); } let mut output = self.output.clone(); output.insert(0, command); output.into() } else { vec!() } } }
use winit_input_helper::{WinitInputHelper, TextChar}; use std::collections::VecDeque; use winit::event::VirtualKeyCode; use treeflection::{Node, NodeRunner, NodeToken}; #[derive(Clone, Default, Serialize, Deserialize, Node)] pub struct CommandLine { history_index: isize, cursor: usize, history: Vec<String>, command: String, output: VecDeque<String>, running: bool, } impl CommandLine { pub fn new() -> Self { Self { history_index: -1, cursor: 0, history: vec!(), command: String::new(), output: VecDeque::new(), running: false, } } pub fn step<T>(&mut self, os_input: &WinitInputHelper, root_node: &mut T) where T: Node { if os_input.key_pressed(VirtualKeyCode::Grave) { self.running = !self.running; return; } if self.running { for text_char in os_input.text() { match text_char { TextChar::Char(new_char) => { let mut new_command = String::new(); let mut hit_cursor = false; for (i, old_char) in self.command.char_indices() {
new_command.push(old_char); } if !hit_cursor { new_command.push(new_char); } self.command = new_command; self.cursor += 1; } TextChar::Back => { if self.cursor > 0 { self.cursor -= 1; let mut new_command = String::new(); for (i, old_char) in self.command.char_indices() { if i != self.cursor { new_command.push(old_char); } } self.command = new_command; } } } self.history_index = -1; } if os_input.key_pressed(VirtualKeyCode::Return) { { let command = format!("→{}", self.command.trim_end()); self.output_add(command); } let result = match NodeRunner::new(self.command.as_str()) { Ok(runner) => root_node.node_step(runner), Err(msg) => msg }; for line in result.split('\n') { self.output_add(line.to_string()); } self.history.insert(0, self.command.trim_end().to_string()); self.history_index = -1; self.command.clear(); self.cursor = 0; } if os_input.key_pressed(VirtualKeyCode::Home) { self.cursor = 0; } if os_input.key_pressed(VirtualKeyCode::End) { self.cursor = self.command.chars().count(); } if os_input.key_pressed(VirtualKeyCode::Left) && self.cursor > 0 { self.cursor -= 1; } if os_input.key_pressed(VirtualKeyCode::Right) && self.cursor < self.command.chars().count() { self.cursor += 1; } if os_input.key_pressed(VirtualKeyCode::Up) && self.history_index + 1 < self.history.len() as isize { self.history_index += 1; self.command = self.history[self.history_index as usize].clone(); self.cursor = self.command.chars().count(); } if os_input.key_pressed(VirtualKeyCode::Down) { if self.history_index > 0 { self.history_index -= 1; self.command = self.history[self.history_index as usize].clone(); self.cursor = self.command.chars().count(); } else if self.history_index == 0 { self.history_index -= 1; self.command.clear(); self.cursor = 0; } } } } fn output_add(&mut self, line: String) { if self.output.len() >= 100 { self.output.pop_back(); } self.output.push_front(line); } pub fn block(&self) -> bool { self.running } pub fn output(&self) -> Vec<String> { if self.running { let mut command = String::from("→"); let mut hit_cursor = false; for (i, c) in self.command.char_indices() { if i == self.cursor { hit_cursor = true; command.push('■'); } command.push(c); } if !hit_cursor { command.push('■'); } let mut output = self.output.clone(); output.insert(0, command); output.into() } else { vec!() } } }
if i == self.cursor { hit_cursor = true; new_command.push(new_char); }
if_condition
[ { "content": "pub fn get_replay_names() -> Vec<String> {\n\n let mut result: Vec<String> = vec!();\n\n \n\n if let Ok(files) = fs::read_dir(get_replays_dir_path()) {\n\n for file in files {\n\n if let Ok(file) = file {\n\n let file_name = file.file_name().into_string()....
Rust
src/http-server.rs
kawakami-o3/learn-http
2d3ba09f2045cb08a333b89e160b9712a4d9299e
extern crate toml; mod conf; mod http_request; mod http_response; mod method; mod status; mod util; use std::fs; use std::io::prelude::*; use std::net::{Shutdown, TcpListener, TcpStream}; use std::path::{Path, PathBuf}; use std::thread; use chrono::Local; use serde::Deserialize; use crate::http_request::*; use crate::http_response::*; const CONF_PATH: &str = "server_conf.json"; const ACCESS_CONF: &str = ".access"; #[derive(Debug, Deserialize)] struct AccessConfig { auth: Option<AuthConfig>, } impl AccessConfig { fn new() -> AccessConfig { AccessConfig { auth: None, } } } #[derive(Debug, Deserialize)] struct AuthConfig { auth_type: String, auth_name: String, pass_file: String, pass_content: Option<String>, } impl AuthConfig { fn is_basic(& self) -> bool { self.auth_type == "Basic" } } fn load_access_config(access_path: & String) -> AccessConfig { let path = Path::new(access_path); let config_path = if path.is_dir() { PathBuf::from(format!("{}/{}", access_path, ACCESS_CONF)) } else { path.with_file_name(ACCESS_CONF) }; if !config_path.exists() { return AccessConfig::new(); } let mut config_content = String::new(); util::read_file(&config_path.to_str().unwrap().to_string(), &mut config_content).unwrap(); let mut config = match toml::from_str(config_content.as_str()) { Ok(c) => c, Err(_) => AccessConfig { auth: None }, }; if config.auth.is_some() { let mut auth = config.auth.unwrap(); if auth.pass_file.len() > 0 { let target = path.with_file_name(&auth.pass_file); let mut buf = String::new(); util::read_file(&target.to_str().unwrap().to_string(), &mut buf).unwrap(); auth.pass_content = Some(buf); } config.auth = Some(auth); } return config; } fn handle_content_info(response: &mut Response, access_path: & String) { match util::extension(&access_path) { Some("ico") => { response.add_header("Content-Type", "image/x-icon".to_string()); response.add_header("Content-Length", format!("{}", response.entity_body.len())); } _ => { response.add_header("Content-Type", "text/html".to_string()); } } } fn handle_basic_authorization(request: &Request, response: &mut Response, auth_config: AuthConfig) { let cred = request.authorization(); if cred.len() < 2 || cred[0] != "Basic" { response.status = status::UNAUTHORIZED; response.add_header("WWW-authenticate", format!("Basic realm=\"{}\"", auth_config.auth_name)); return; } let user_pass = String::from_utf8(base64::decode(cred[1]).unwrap()).unwrap(); let matched = auth_config.pass_content.unwrap().split('\n').any(|i| i == user_pass); if !matched { response.status = status::UNAUTHORIZED; response.add_header("WWW-authenticate", format!("Basic realm=\"{}\"", auth_config.auth_name)); return; } } fn handle(request: &Request, response: &mut Response) -> Result<(), String> { response.version = request.version.clone(); response.set_host(format!("{}:{}", conf::ip(), conf::port())); response.set_server(conf::server()); let date_str = Local::now().to_rfc2822(); response.add_header("Date", format!("{} GMT", &date_str[..date_str.len() - 6])); println!("request: {:?}", request); println!("authorization: {:?}", request.authorization()); match request.uri.as_str() { "/debug" => { response.entity_body.append(&mut request.bytes()); } request_uri => { let uri = match util::canonicalize(request_uri) { Some(s) => s, None => { println!( "debug(403)1: {}", format!("{}{}", conf::root(), request_uri) ); response.status = status::FORBIDDEN; return Ok(()); } }; let access_target = format!("{}{}", conf::root(), uri); let access_path = Path::new(&access_target); let access_config = load_access_config(&access_target); if let Some(auth_config) = access_config.auth { if auth_config.is_basic() { handle_basic_authorization(request, response, auth_config); return Ok(()) } } if !access_path.exists() { println!("debug(404): {}", format!("{}{}", conf::root(), uri)); response.status = status::NOT_FOUND; return Ok(()); } if access_path.is_dir() { unsafe { response.entity_body.append(access_target.clone().as_mut_vec()); } return Ok(()); } match fs::read(access_path) { Ok(mut v) => { response.entity_body.append(&mut v); } Err(e) => { println!("debug(403)2: {} {}", format!("{}{}", conf::root(), uri), e); response.status = status::FORBIDDEN; return Ok(()); } } match util::modified(&access_target) { Ok(t) => { response.modified_datetime = Some(t); response.add_header("Last-Modified", util::datetime_to_http_date(&t)); } Err(_) => { println!("debug(503)1: {}", format!("{}{}", conf::root(), uri)); response.status = status::INTERNAL_SERVER_ERROR; return Ok(()); } }; match request.if_modified_since() { Some(s) => { match response.modified_datetime { Some(t) => { if s > t { response.status = status::NOT_MODIFIED; return Ok(()); } } None => { } } } None => { } }; handle_content_info(response, &access_target); } } Ok(()) } fn handle_request(mut stream: TcpStream) { let mut buf = vec![0; 1024]; let mut request = http_request::new(); match stream.read(&mut buf) { Ok(n) => { if n == 0 { println!("shutdown"); stream.shutdown(Shutdown::Both).unwrap(); return; } match request.parse(&mut buf[0..n].to_vec()) { Ok(()) => {} Err(e) => { println!("{}", e); stream.shutdown(Shutdown::Both).unwrap(); return; } } } Err(e) => { println!("ERR: {:?}", e); stream.shutdown(Shutdown::Both).unwrap(); return; } } let response = &mut http_response::new(); match handle(&request, response) { Ok(()) => { stream.write(response.to_bytes().as_slice()).unwrap(); } Err(e) => { println!("ERR: {:?}", e); stream.shutdown(Shutdown::Both).unwrap(); return; } } } fn main() -> std::io::Result<()> { let server_conf = conf::load(CONF_PATH); conf::set(server_conf.clone()); let listener = TcpListener::bind(format!("127.0.0.1:{}", conf::port()))?; match listener.local_addr() { Ok(addr) => { println!("starting ... {}:{}", addr.ip(), addr.port()); } Err(e) => { panic!("Error(local_addr): {}", e); } } /* for stream in listener.incoming() { match stream { Ok(mut stream) => { handle_request(&mut stream); } Err(e) => { println!("ERR: {:?}", e); } } } Ok(()) */ loop { let (stream, _) = listener.accept()?; let proc = |cnf, stream| { return || { conf::set(cnf); handle_request(stream); }; }; thread::spawn(proc(server_conf.clone(), stream)); } }
extern crate toml; mod conf; mod http_request; mod http_response; mod method; mod status; mod util; use std::fs; use std::io::prelude::*; use std::net::{Shutdown, TcpListener, TcpStream}; use std::path::{Path, PathBuf}; use std::thread; use chrono::Local; use serde::Deserialize; use crate::http_request::*; use crate::http_response::*; const CONF_PATH: &str = "server_conf.json"; const ACCESS_CONF: &str = ".access"; #[derive(Debug, Deserialize)] struct AccessConfig { auth: Option<AuthConfig>, } impl AccessConfig { fn new() -> AccessConfig { AccessConfig { auth: None, } } } #[derive(Debug, Deserialize)] struct AuthConfig { auth_type: String, auth_name: String, pass_file: String, pass_content: Option<String>, } impl AuthConfig { fn is_basic(& self) -> bool { self.auth_type == "Basic" } }
fn handle_content_info(response: &mut Response, access_path: & String) { match util::extension(&access_path) { Some("ico") => { response.add_header("Content-Type", "image/x-icon".to_string()); response.add_header("Content-Length", format!("{}", response.entity_body.len())); } _ => { response.add_header("Content-Type", "text/html".to_string()); } } } fn handle_basic_authorization(request: &Request, response: &mut Response, auth_config: AuthConfig) { let cred = request.authorization(); if cred.len() < 2 || cred[0] != "Basic" { response.status = status::UNAUTHORIZED; response.add_header("WWW-authenticate", format!("Basic realm=\"{}\"", auth_config.auth_name)); return; } let user_pass = String::from_utf8(base64::decode(cred[1]).unwrap()).unwrap(); let matched = auth_config.pass_content.unwrap().split('\n').any(|i| i == user_pass); if !matched { response.status = status::UNAUTHORIZED; response.add_header("WWW-authenticate", format!("Basic realm=\"{}\"", auth_config.auth_name)); return; } } fn handle(request: &Request, response: &mut Response) -> Result<(), String> { response.version = request.version.clone(); response.set_host(format!("{}:{}", conf::ip(), conf::port())); response.set_server(conf::server()); let date_str = Local::now().to_rfc2822(); response.add_header("Date", format!("{} GMT", &date_str[..date_str.len() - 6])); println!("request: {:?}", request); println!("authorization: {:?}", request.authorization()); match request.uri.as_str() { "/debug" => { response.entity_body.append(&mut request.bytes()); } request_uri => { let uri = match util::canonicalize(request_uri) { Some(s) => s, None => { println!( "debug(403)1: {}", format!("{}{}", conf::root(), request_uri) ); response.status = status::FORBIDDEN; return Ok(()); } }; let access_target = format!("{}{}", conf::root(), uri); let access_path = Path::new(&access_target); let access_config = load_access_config(&access_target); if let Some(auth_config) = access_config.auth { if auth_config.is_basic() { handle_basic_authorization(request, response, auth_config); return Ok(()) } } if !access_path.exists() { println!("debug(404): {}", format!("{}{}", conf::root(), uri)); response.status = status::NOT_FOUND; return Ok(()); } if access_path.is_dir() { unsafe { response.entity_body.append(access_target.clone().as_mut_vec()); } return Ok(()); } match fs::read(access_path) { Ok(mut v) => { response.entity_body.append(&mut v); } Err(e) => { println!("debug(403)2: {} {}", format!("{}{}", conf::root(), uri), e); response.status = status::FORBIDDEN; return Ok(()); } } match util::modified(&access_target) { Ok(t) => { response.modified_datetime = Some(t); response.add_header("Last-Modified", util::datetime_to_http_date(&t)); } Err(_) => { println!("debug(503)1: {}", format!("{}{}", conf::root(), uri)); response.status = status::INTERNAL_SERVER_ERROR; return Ok(()); } }; match request.if_modified_since() { Some(s) => { match response.modified_datetime { Some(t) => { if s > t { response.status = status::NOT_MODIFIED; return Ok(()); } } None => { } } } None => { } }; handle_content_info(response, &access_target); } } Ok(()) } fn handle_request(mut stream: TcpStream) { let mut buf = vec![0; 1024]; let mut request = http_request::new(); match stream.read(&mut buf) { Ok(n) => { if n == 0 { println!("shutdown"); stream.shutdown(Shutdown::Both).unwrap(); return; } match request.parse(&mut buf[0..n].to_vec()) { Ok(()) => {} Err(e) => { println!("{}", e); stream.shutdown(Shutdown::Both).unwrap(); return; } } } Err(e) => { println!("ERR: {:?}", e); stream.shutdown(Shutdown::Both).unwrap(); return; } } let response = &mut http_response::new(); match handle(&request, response) { Ok(()) => { stream.write(response.to_bytes().as_slice()).unwrap(); } Err(e) => { println!("ERR: {:?}", e); stream.shutdown(Shutdown::Both).unwrap(); return; } } } fn main() -> std::io::Result<()> { let server_conf = conf::load(CONF_PATH); conf::set(server_conf.clone()); let listener = TcpListener::bind(format!("127.0.0.1:{}", conf::port()))?; match listener.local_addr() { Ok(addr) => { println!("starting ... {}:{}", addr.ip(), addr.port()); } Err(e) => { panic!("Error(local_addr): {}", e); } } /* for stream in listener.incoming() { match stream { Ok(mut stream) => { handle_request(&mut stream); } Err(e) => { println!("ERR: {:?}", e); } } } Ok(()) */ loop { let (stream, _) = listener.accept()?; let proc = |cnf, stream| { return || { conf::set(cnf); handle_request(stream); }; }; thread::spawn(proc(server_conf.clone(), stream)); } }
fn load_access_config(access_path: & String) -> AccessConfig { let path = Path::new(access_path); let config_path = if path.is_dir() { PathBuf::from(format!("{}/{}", access_path, ACCESS_CONF)) } else { path.with_file_name(ACCESS_CONF) }; if !config_path.exists() { return AccessConfig::new(); } let mut config_content = String::new(); util::read_file(&config_path.to_str().unwrap().to_string(), &mut config_content).unwrap(); let mut config = match toml::from_str(config_content.as_str()) { Ok(c) => c, Err(_) => AccessConfig { auth: None }, }; if config.auth.is_some() { let mut auth = config.auth.unwrap(); if auth.pass_file.len() > 0 { let target = path.with_file_name(&auth.pass_file); let mut buf = String::new(); util::read_file(&target.to_str().unwrap().to_string(), &mut buf).unwrap(); auth.pass_content = Some(buf); } config.auth = Some(auth); } return config; }
function_block-full_function
[ { "content": "pub fn canonicalize(s: &str) -> Option<String> {\n\n let mut v: Vec<&str> = Vec::new();\n\n for i in s.split(\"/\") {\n\n match i {\n\n \"\" => {\n\n if v.len() == 0 {\n\n v.push(\"\");\n\n }\n\n }\n\n \...
Rust
exonum/src/runtime/dispatcher/schema.rs
SergeiMal/exonum
520324a321462bceb8acda9a92b9ed63fcdc3eaf
use exonum_merkledb::{ access::{Access, AccessExt, AsReadonly}, Fork, KeySetIndex, MapIndex, ProofMapIndex, }; use super::{ArtifactId, Error, InstanceSpec}; use crate::runtime::{ ArtifactState, ArtifactStatus, InstanceId, InstanceQuery, InstanceState, InstanceStatus, }; const ARTIFACTS: &str = "dispatcher_artifacts"; const PENDING_ARTIFACTS: &str = "dispatcher_pending_artifacts"; const INSTANCES: &str = "dispatcher_instances"; const PENDING_INSTANCES: &str = "dispatcher_pending_instances"; const INSTANCE_IDS: &str = "dispatcher_instance_ids"; #[derive(Debug)] pub struct Schema<T: Access> { access: T, } impl<T: Access> Schema<T> { pub(crate) fn new(access: T) -> Self { Self { access } } pub(crate) fn artifacts(&self) -> ProofMapIndex<T::Base, ArtifactId, ArtifactState> { self.access.clone().get_proof_map(ARTIFACTS) } pub(crate) fn instances(&self) -> ProofMapIndex<T::Base, str, InstanceState> { self.access.clone().get_proof_map(INSTANCES) } fn instance_ids(&self) -> MapIndex<T::Base, InstanceId, String> { self.access.clone().get_map(INSTANCE_IDS) } fn pending_artifacts(&self) -> KeySetIndex<T::Base, ArtifactId> { self.access.clone().get_key_set(PENDING_ARTIFACTS) } fn modified_instances(&self) -> MapIndex<T::Base, str, InstanceStatus> { self.access.clone().get_map(PENDING_INSTANCES) } pub fn get_instance<'q>(&self, query: impl Into<InstanceQuery<'q>>) -> Option<InstanceState> { let instances = self.instances(); match query.into() { InstanceQuery::Id(id) => self .instance_ids() .get(&id) .and_then(|instance_name| instances.get(&instance_name)), InstanceQuery::Name(instance_name) => instances.get(instance_name), } } pub fn get_artifact(&self, name: &ArtifactId) -> Option<ArtifactState> { self.artifacts().get(name) } } impl<T: AsReadonly> Schema<T> { pub fn service_instances(&self) -> ProofMapIndex<T::Readonly, String, InstanceState> { self.access.as_readonly().get_proof_map(INSTANCES) } } impl Schema<&Fork> { pub(super) fn add_pending_artifact( &mut self, artifact: ArtifactId, deploy_spec: Vec<u8>, ) -> Result<(), Error> { if self.artifacts().contains(&artifact) { return Err(Error::ArtifactAlreadyDeployed); } self.artifacts().put( &artifact, ArtifactState { deploy_spec, status: ArtifactStatus::Pending, }, ); self.pending_artifacts().insert(artifact); Ok(()) } pub(crate) fn initiate_adding_service(&mut self, spec: InstanceSpec) -> Result<(), Error> { self.artifacts() .get(&spec.artifact) .ok_or(Error::ArtifactNotDeployed)?; let mut instances = self.instances(); let mut instance_ids = self.instance_ids(); if instances.contains(&spec.name) { return Err(Error::ServiceNameExists); } if instance_ids.contains(&spec.id) { return Err(Error::ServiceIdExists); } let instance_id = spec.id; let instance_name = spec.name.clone(); let pending_status = InstanceStatus::Active; instances.put( &instance_name, InstanceState { spec, status: None, pending_status: Some(pending_status), }, ); self.modified_instances() .put(&instance_name, pending_status); instance_ids.put(&instance_id, instance_name); Ok(()) } pub(crate) fn initiate_stopping_service( &mut self, instance_id: InstanceId, ) -> Result<(), Error> { let mut instances = self.instances(); let mut modified_instances = self.modified_instances(); let instance_name = self .instance_ids() .get(&instance_id) .ok_or(Error::IncorrectInstanceId)?; let mut state = instances .get(&instance_name) .expect("BUG: Instance identifier exists but the corresponding instance is missing."); match state.status { Some(InstanceStatus::Active) => {} _ => return Err(Error::ServiceNotActive), } if state.pending_status.is_some() { return Err(Error::ServicePending); } let pending_status = InstanceStatus::Stopped; state.pending_status = Some(pending_status); modified_instances.put(&instance_name, pending_status); instances.put(&instance_name, state); Ok(()) } pub(super) fn activate_pending(&mut self) { let mut artifacts = self.artifacts(); for artifact in &self.pending_artifacts() { let mut state = artifacts .get(&artifact) .expect("Artifact marked as pending is not saved in `artifacts`"); state.status = ArtifactStatus::Active; artifacts.put(&artifact, state); } let mut instances = self.instances(); for (instance, status) in &self.modified_instances() { let mut state = instances .get(&instance) .expect("BUG: Instance marked as modified is not saved in `instances`"); debug_assert_eq!( Some(status), state.pending_status, "BUG: Instance status in `modified_instances` should be same as `pending_status` \ in the instance state." ); state.commit_pending_status(); instances.put(&instance, state); } } pub(super) fn take_pending_artifacts(&mut self) -> Vec<(ArtifactId, Vec<u8>)> { let mut index = self.pending_artifacts(); let artifacts = self.artifacts(); let pending_artifacts = index .iter() .map(|artifact| { let deploy_spec = artifacts .get(&artifact) .expect("Artifact marked as pending is not saved in `artifacts`") .deploy_spec; (artifact, deploy_spec) }) .collect(); index.clear(); pending_artifacts } pub(super) fn take_modified_instances(&mut self) -> Vec<(InstanceSpec, InstanceStatus)> { let mut modified_instances = self.modified_instances(); let instances = self.instances(); let output = modified_instances .iter() .map(|(instance_name, status)| { let state = instances .get(&instance_name) .expect("BUG: Instance marked as modified is not saved in `instances`"); (state.spec, status) }) .collect::<Vec<_>>(); modified_instances.clear(); output } }
use exonum_merkledb::{ access::{Access, AccessExt, AsReadonly}, Fork, KeySetIndex, MapIndex, ProofMapIndex, }; use super::{ArtifactId, Error, InstanceSpec}; use crate::runtime::{ ArtifactState, ArtifactStatus, InstanceId, InstanceQuery, InstanceState, InstanceStatus, }; const ARTIFACTS: &str = "dispatcher_artifacts"; const PENDING_ARTIFACTS: &str = "dispatcher_pending_artifacts"; const INSTANCES: &str = "dispatcher_instances"; const PENDING_INSTANCES: &str = "dispatcher_pending_instances"; const INSTANCE_IDS: &str = "dispatcher_instance_ids"; #[derive(Debug)] pub struct Schema<T: Access> { access: T, } impl<T: Access> Schema<T> { pub(crate) fn new(access: T) -> Self { Self { access } } pub(crate) fn artifacts(&self) -> ProofMapIndex<T::Base, ArtifactId, ArtifactState> { self.access.clone().get_proof_map(ARTIFACTS) } pub(crate) fn instances(&self) -> ProofMapIndex<T::Base, str, InstanceState> { self.access.clone().get_proof_map(INSTANCES) } fn instance_ids(&self) -> MapIndex<T::Base, InstanceId, String> { self.access.clone().get_map(INSTANCE_IDS) } fn pending_artifacts(&self) -> KeySetIndex<T::Base, ArtifactId> { self.access.clone().get_key_set(PENDING_ARTIFACTS) } fn modified_instances(&self) -> MapIndex<T::Base, str, InstanceStatus> { self.access.clone().get_map(PENDING_INSTANCES) } pub fn get_instance<'q>(&self, query: impl Into<InstanceQuery<'q>>) -> Option<InstanceState> { let instances = self.instances(); match query.into() { InstanceQuery::Id(id) => self .instance_ids() .get(&id) .and_then(|instance_name| instances.get(&instance_name)), InstanceQuery::Name(instance_name) => instances.get(instance_name), } } pub fn get_artifact(&self, name: &ArtifactId) -> Option<ArtifactState> { self.artifacts().get(name) } } impl<T: AsReadonly> Schema<T> { pub fn service_instances(&self) -> ProofMapIndex<T::Readonly, String, InstanceState> { self.access.as_readonly().get_proof_map(INSTANCES) } } impl Schema<&Fork> { pub(super) fn add_pending_artifact( &mut self, artifact: ArtifactId, deploy_spec: Vec<u8>, ) -> Result<(), Error> { if self.artifacts().contains(&artifact) { return Err(Error::ArtifactAlreadyDeployed); } self.artifacts().put( &artifact, ArtifactState { deploy_spec, status: ArtifactStatus::Pending, }, ); self.pending_artifacts().insert(artifact); Ok(()) } pub(crate) fn initiate_adding_service(&mut self, spec: InstanceSpec) -> Result<(), Error> { self.artifacts() .get(&spec.artifact) .ok_or(Error::ArtifactNotDeployed)?; let mut instances = self.instances(); let mut instance_ids = self.instance_ids(); if instances.contains(&spec.name) { return Err(Error::ServiceNameExists); } if instance_ids.contains(&spec.id) { return Err(Error::ServiceIdExists); } let instance_id = spec.id; let instance_name = spec.name.clone(); let pending_status = InstanceStatus::Active; instances.put( &instance_name, InstanceState { spec, status: None, pending_status: Some(pending_status), }, ); self.modified_instances() .put(&instance_name, pending_status); instance_ids.put(&instance_id, instance_name); Ok(()) } pub(crate) fn initiate_stopping_service( &mut self, instance_id: InstanceId, ) -> Result<(), Error> { let mut instances = self.instances(); let mut modified_instances = self.modified_instances(); let instance_name = self .instance_ids() .get(&instance_id) .ok_or(Error::IncorrectInstanceId)?; let mut state = instances .get(&instance_name) .expect("BUG: Instance identifier exists but the corresponding instance is missing."); match state.status { Some(InstanceStatus::Active) => {} _ => return Err(Error::ServiceNotActive), } if state.pending_status.is_some() { return Err(Error::ServicePending); } let pending_status = InstanceStatus::Stopped; state.pending_status = Some(pending_status); modified_instances.put(&instance_name, pending_status); instances.put(&instance_name, state); Ok(()) } pub(super) fn activate_pending(&mut self) { let mut artifacts = self.artifacts(); for artifact in &self.pending_artifacts() { let mut state = artifacts .get(&artifact) .expect("Artifact marked as pending is not saved in `artifacts`"); state.status = ArtifactStatus::Active; artifacts.put(&artifact, state); } let mut instances = self.instances(); for (instance, status) in &self.modified_instances() { let mut state = instances .get(&instance) .expect("BUG: Instance marked as modified is not saved in `instances`"); debug_assert_eq!( Some(status), state.pending_status, "BUG: Instance status in `modified_instances` should be same as `pending_status` \ in the instance state." ); state.commit_pending_status(); instances.put(&instance, state); } } pub(super) fn take_pending_artifacts(&mut self) -> Vec<(ArtifactId, Vec<u8>)> { let mut index = self.pending_artifacts(); let artifacts = self.artifacts(); let pending_artifacts = index .iter() .map(|artifact| { let deploy_spec = artifacts .get(&artifact) .expect("Artifact marked as pending is not saved in `artifacts`") .deploy_spec; (artifact, deploy_spec) }) .collect(); index.clear(); pending_artifacts }
}
pub(super) fn take_modified_instances(&mut self) -> Vec<(InstanceSpec, InstanceStatus)> { let mut modified_instances = self.modified_instances(); let instances = self.instances(); let output = modified_instances .iter() .map(|(instance_name, status)| { let state = instances .get(&instance_name) .expect("BUG: Instance marked as modified is not saved in `instances`"); (state.spec, status) }) .collect::<Vec<_>>(); modified_instances.clear(); output }
function_block-full_function
[ { "content": "pub fn result_ok<T>(_: T) -> Result<(), Error> {\n\n Ok(())\n\n}\n\n\n", "file_path": "exonum/src/events/error.rs", "rank": 0, "score": 391754.5381453211 }, { "content": "fn validate_address_component(name: &str) -> Result<(), String> {\n\n if name.is_empty() {\n\n ...
Rust
src/resolver.rs
touilleMan/rstest
d3284c7baae78e58f06db9c4ca7f4f2bad5fc50e
use std::borrow::Cow; use std::collections::HashMap; use proc_macro2::Ident; use syn::{parse_quote, Expr}; use crate::parse::Fixture; pub(crate) mod fixtures { use quote::format_ident; use super::*; pub(crate) fn get<'a>(fixtures: impl Iterator<Item = &'a Fixture>) -> impl Resolver + 'a { fixtures .map(|f| (f.name.to_string(), extract_resolve_expression(f))) .collect::<HashMap<_, Expr>>() } fn extract_resolve_expression(fixture: &Fixture) -> syn::Expr { let resolve = fixture.resolve.as_ref().unwrap_or(&fixture.name); let positional = &fixture.positional.0; let f_name = match positional.len() { 0 => format_ident!("default"), l => format_ident!("partial_{}", l), }; parse_quote! { #resolve::#f_name(#(#positional), *) } } #[cfg(test)] mod should { use super::*; use crate::test::{assert_eq, *}; #[rstest] #[case(&[], "default()")] #[case(&["my_expression"], "partial_1(my_expression)")] #[case(&["first", "other"], "partial_2(first, other)")] fn resolve_by_use_the_given_name(#[case] args: &[&str], #[case] expected: &str) { let data = vec![fixture("pippo", args)]; let resolver = get(data.iter()); let resolved = resolver.resolve(&ident("pippo")).unwrap().into_owned(); assert_eq!(resolved, format!("pippo::{}", expected).ast()); } #[rstest] #[case(&[], "default()")] #[case(&["my_expression"], "partial_1(my_expression)")] #[case(&["first", "other"], "partial_2(first, other)")] fn resolve_by_use_the_resolve_field(#[case] args: &[&str], #[case] expected: &str) { let data = vec![fixture("pippo", args).with_resolve("pluto")]; let resolver = get(data.iter()); let resolved = resolver.resolve(&ident("pippo")).unwrap().into_owned(); assert_eq!(resolved, format!("pluto::{}", expected).ast()); } } } pub(crate) mod values { use super::*; use crate::parse::fixture::ArgumentValue; pub(crate) fn get<'a>(values: impl Iterator<Item = &'a ArgumentValue>) -> impl Resolver + 'a { values .map(|av| (av.name.to_string(), &av.expr)) .collect::<HashMap<_, &'a Expr>>() } #[cfg(test)] mod should { use super::*; use crate::test::{assert_eq, *}; #[test] fn resolve_by_use_the_given_name() { let data = vec![ arg_value("pippo", "42"), arg_value("donaldduck", "vec![1,2]"), ]; let resolver = get(data.iter()); assert_eq!( resolver.resolve(&ident("pippo")).unwrap().into_owned(), "42".ast() ); assert_eq!( resolver.resolve(&ident("donaldduck")).unwrap().into_owned(), "vec![1,2]".ast() ); } } } pub(crate) trait Resolver { fn resolve(&self, ident: &Ident) -> Option<Cow<Expr>>; } impl<'a> Resolver for HashMap<String, &'a Expr> { fn resolve(&self, ident: &Ident) -> Option<Cow<Expr>> { let ident = ident.to_string(); self.get(&ident).map(|&c| Cow::Borrowed(c)) } } impl<'a> Resolver for HashMap<String, Expr> { fn resolve(&self, ident: &Ident) -> Option<Cow<Expr>> { let ident = ident.to_string(); self.get(&ident).map(Cow::Borrowed) } } impl<R1: Resolver, R2: Resolver> Resolver for (R1, R2) { fn resolve(&self, ident: &Ident) -> Option<Cow<Expr>> { self.0.resolve(ident).or_else(|| self.1.resolve(ident)) } } impl<R: Resolver + ?Sized> Resolver for &R { fn resolve(&self, ident: &Ident) -> Option<Cow<Expr>> { (*self).resolve(ident) } } impl<R: Resolver + ?Sized> Resolver for Box<R> { fn resolve(&self, ident: &Ident) -> Option<Cow<Expr>> { (**self).resolve(ident) } } impl Resolver for (String, Expr) { fn resolve(&self, ident: &Ident) -> Option<Cow<Expr>> { if *ident == self.0 { Some(Cow::Borrowed(&self.1)) } else { None } } } #[cfg(test)] mod should { use super::*; use crate::test::{assert_eq, *}; use syn::parse_str; #[test] fn return_the_given_expression() { let ast = parse_str("fn function(mut foo: String) {}").unwrap(); let arg = first_arg_ident(&ast); let expected = expr("bar()"); let mut resolver = HashMap::new(); resolver.insert("foo".to_string(), &expected); assert_eq!(expected, (&resolver).resolve(&arg).unwrap().into_owned()) } #[test] fn return_none_for_unknown_argument() { let ast = "fn function(mut fix: String) {}".ast(); let arg = first_arg_ident(&ast); assert!(EmptyResolver.resolve(&arg).is_none()) } }
use std::borrow::Cow; use std::collections::HashMap; use proc_macro2::Ident; use syn::{parse_quote, Expr}; use crate::parse::Fixture; pub(crate) mod fixtures { use quote::format_ident; use super::*; pub(crate) fn get<'a>(fixtures: impl Iterator<Item = &'a Fixture>) -> impl Resolver + 'a { fixtures .map(|f| (f.name.to_string(), extract_resolve_expression(f))) .collect::<HashMap<_, Expr>>() } fn extract_resolve_expression(fixture: &Fixture) -> syn::Expr { let resolve = fixture.resolve.as_ref().unwrap_or(&fixture.name); let positional = &fixture.positional.0; let f_name = match positional.len() { 0 => format_ident!("default"), l => format_ident!("partial_{}", l), }; parse_quote! { #resolve::#f_name(#(#positional), *) } } #[cfg(test)] mod should { use super::*; use crate::test::{assert_eq, *}; #[rstest] #[case(&[], "default()")] #[case(&["my_expression"], "partial_1(my_expression)")] #[case(&["first", "other"], "partial_2(first, other)")] fn resolve_by_use_the_given_name(#[case] args: &[&str], #[case] expected: &str) { let data = vec![fixture("pippo", args)]; let resolver = get(data.iter()); let resolved = resolver.resolve(&ident("pippo")).unwrap().into_owned(); assert_eq!(resolved, format!("pippo::{}", expected).ast()); } #[rstest] #[case(&[], "default()")] #[case(&["my_expression"], "partial_1(my_expression)")] #[case(&["first", "other"], "partial_2(first, other)")]
} } pub(crate) mod values { use super::*; use crate::parse::fixture::ArgumentValue; pub(crate) fn get<'a>(values: impl Iterator<Item = &'a ArgumentValue>) -> impl Resolver + 'a { values .map(|av| (av.name.to_string(), &av.expr)) .collect::<HashMap<_, &'a Expr>>() } #[cfg(test)] mod should { use super::*; use crate::test::{assert_eq, *}; #[test] fn resolve_by_use_the_given_name() { let data = vec![ arg_value("pippo", "42"), arg_value("donaldduck", "vec![1,2]"), ]; let resolver = get(data.iter()); assert_eq!( resolver.resolve(&ident("pippo")).unwrap().into_owned(), "42".ast() ); assert_eq!( resolver.resolve(&ident("donaldduck")).unwrap().into_owned(), "vec![1,2]".ast() ); } } } pub(crate) trait Resolver { fn resolve(&self, ident: &Ident) -> Option<Cow<Expr>>; } impl<'a> Resolver for HashMap<String, &'a Expr> { fn resolve(&self, ident: &Ident) -> Option<Cow<Expr>> { let ident = ident.to_string(); self.get(&ident).map(|&c| Cow::Borrowed(c)) } } impl<'a> Resolver for HashMap<String, Expr> { fn resolve(&self, ident: &Ident) -> Option<Cow<Expr>> { let ident = ident.to_string(); self.get(&ident).map(Cow::Borrowed) } } impl<R1: Resolver, R2: Resolver> Resolver for (R1, R2) { fn resolve(&self, ident: &Ident) -> Option<Cow<Expr>> { self.0.resolve(ident).or_else(|| self.1.resolve(ident)) } } impl<R: Resolver + ?Sized> Resolver for &R { fn resolve(&self, ident: &Ident) -> Option<Cow<Expr>> { (*self).resolve(ident) } } impl<R: Resolver + ?Sized> Resolver for Box<R> { fn resolve(&self, ident: &Ident) -> Option<Cow<Expr>> { (**self).resolve(ident) } } impl Resolver for (String, Expr) { fn resolve(&self, ident: &Ident) -> Option<Cow<Expr>> { if *ident == self.0 { Some(Cow::Borrowed(&self.1)) } else { None } } } #[cfg(test)] mod should { use super::*; use crate::test::{assert_eq, *}; use syn::parse_str; #[test] fn return_the_given_expression() { let ast = parse_str("fn function(mut foo: String) {}").unwrap(); let arg = first_arg_ident(&ast); let expected = expr("bar()"); let mut resolver = HashMap::new(); resolver.insert("foo".to_string(), &expected); assert_eq!(expected, (&resolver).resolve(&arg).unwrap().into_owned()) } #[test] fn return_none_for_unknown_argument() { let ast = "fn function(mut fix: String) {}".ast(); let arg = first_arg_ident(&ast); assert!(EmptyResolver.resolve(&arg).is_none()) } }
fn resolve_by_use_the_resolve_field(#[case] args: &[&str], #[case] expected: &str) { let data = vec![fixture("pippo", args).with_resolve("pluto")]; let resolver = get(data.iter()); let resolved = resolver.resolve(&ident("pippo")).unwrap().into_owned(); assert_eq!(resolved, format!("pluto::{}", expected).ast()); }
function_block-function_prefix_line
[ { "content": "fn just_args(#[case] expected: usize, #[case] input: &str) {\n\n assert_eq!(expected, input.len());\n\n}\n\n\n", "file_path": "tests/resources/rstest/cases/use_attr.rs", "rank": 0, "score": 311212.7762329668 }, { "content": "#[rstest]\n\n#[case::ciao(4, \"ciao\")]\n\n#[shoul...
Rust
src/types/database.rs
mrijkeboer/rust-kpdb
219410279ee104b3c9c59c17ceef23d0f4f41ef0
use chrono::{DateTime, UTC}; use common; use format::{kdb2_reader, kdb2_writer}; use io::{Log, LogReader, LogWriter}; use std::io::{Read, Write}; use super::binaries_map::BinariesMap; use super::color::Color; use super::comment::Comment; use super::composite_key::CompositeKey; use super::compression::Compression; use super::custom_data_map::CustomDataMap; use super::custom_icons_map::CustomIconsMap; use super::db_type::DbType; use super::entries_map::EntriesMap; use super::error::Error; use super::group::Group; use super::group_uuid::GroupUuid; use super::groups_map::GroupsMap; use super::history_map::HistoryMap; use super::icon::Icon; use super::master_cipher::MasterCipher; use super::result::Result; use super::stream_cipher::StreamCipher; use super::transform_rounds::TransformRounds; use super::version::Version; #[derive(Clone, Debug, PartialEq)] pub struct Database { pub comment: Option<Comment>, pub composite_key: CompositeKey, pub compression: Compression, pub db_type: DbType, pub master_cipher: MasterCipher, pub stream_cipher: StreamCipher, pub transform_rounds: TransformRounds, pub version: Version, pub binaries: BinariesMap, pub color: Option<Color>, pub custom_data: CustomDataMap, pub custom_icons: CustomIconsMap, pub def_username: String, pub def_username_changed: DateTime<UTC>, pub description: String, pub description_changed: DateTime<UTC>, pub entries: EntriesMap, pub entry_templates_group_changed: DateTime<UTC>, pub entry_templates_group_uuid: GroupUuid, pub generator: String, pub group_uuid: Option<GroupUuid>, pub groups: GroupsMap, pub history: HistoryMap, pub history_max_items: i32, pub history_max_size: i32, pub last_selected_group: GroupUuid, pub last_top_visible_group: GroupUuid, pub maintenance_history_days: i32, pub master_key_change_force: i32, pub master_key_change_rec: i32, pub master_key_changed: DateTime<UTC>, pub name: String, pub name_changed: DateTime<UTC>, pub protect_notes: bool, pub protect_password: bool, pub protect_title: bool, pub protect_url: bool, pub protect_username: bool, pub recycle_bin_changed: DateTime<UTC>, pub recycle_bin_enabled: bool, pub recycle_bin_uuid: GroupUuid, } impl Database { pub fn new(key: &CompositeKey) -> Database { let now = UTC::now(); let mut root = Group::new(common::ROOT_GROUP_NAME); let mut recycle_bin = Group::new(common::RECYCLE_BIN_NAME); let mut groups = GroupsMap::new(); recycle_bin.enable_auto_type = Some(false); recycle_bin.enable_searching = Some(false); recycle_bin.icon = Icon::RecycleBin; let root_uuid = root.uuid; let recycle_bin_uuid = recycle_bin.uuid; root.groups.push(recycle_bin_uuid); groups.insert(root_uuid, root); groups.insert(recycle_bin_uuid, recycle_bin); Database { comment: None, composite_key: key.clone(), compression: Compression::GZip, db_type: DbType::Kdb2, master_cipher: MasterCipher::Aes256, stream_cipher: StreamCipher::Salsa20, transform_rounds: TransformRounds(10000), version: Version::new_kdb2(), binaries: BinariesMap::new(), color: None, custom_data: CustomDataMap::new(), custom_icons: CustomIconsMap::new(), def_username: String::new(), def_username_changed: now, description: String::new(), description_changed: now, entries: EntriesMap::new(), entry_templates_group_changed: now, entry_templates_group_uuid: GroupUuid::nil(), generator: String::from(common::GENERATOR_NAME), group_uuid: Some(root_uuid), groups: groups, history: HistoryMap::new(), history_max_items: common::HISTORY_MAX_ITEMS_DEFAULT, history_max_size: common::HISTORY_MAX_SIZE_DEFAULT, last_selected_group: GroupUuid::nil(), last_top_visible_group: GroupUuid::nil(), maintenance_history_days: common::MAINTENANCE_HISTORY_DAYS_DEFAULT, master_key_change_force: common::MASTER_KEY_CHANGE_FORCE_DEFAULT, master_key_change_rec: common::MASTER_KEY_CHANGE_REC_DEFAULT, master_key_changed: now, name: String::new(), name_changed: now, protect_notes: common::PROTECT_NOTES_DEFAULT, protect_password: common::PROTECT_PASSWORD_DEFAULT, protect_title: common::PROTECT_TITLE_DEFAULT, protect_url: common::PROTECT_URL_DEFAULT, protect_username: common::PROTECT_USERNAME_DEFAULT, recycle_bin_changed: now, recycle_bin_enabled: common::RECYCLE_BIN_ENABLED_DEFAULT, recycle_bin_uuid: recycle_bin_uuid, } } pub fn open<R: Read>(reader: &mut R, key: &CompositeKey) -> Result<Database> { let mut reader = LogReader::new(reader); let mut buffer = [0u8; 4]; try!(reader.read(&mut buffer)); if buffer != common::DB_SIGNATURE { return Err(Error::InvalidDbSignature(buffer)); } try!(reader.read(&mut buffer)); if buffer == common::KDB1_SIGNATURE { return Err(Error::UnhandledDbType(buffer)); } else if buffer == common::KDB2_SIGNATURE { Database::open_kdb2(&mut reader, key) } else { return Err(Error::UnhandledDbType(buffer)); } } pub fn save<W: Write>(&self, writer: &mut W) -> Result<()> { let mut writer = LogWriter::new(writer); match self.db_type { DbType::Kdb1 => Err(Error::Unimplemented(String::from("KeePass v1 not supported"))), DbType::Kdb2 => kdb2_writer::write(&mut writer, self), } } fn open_kdb2<R: Log + Read>(reader: &mut R, key: &CompositeKey) -> Result<Database> { let (meta_data, xml_data) = try!(kdb2_reader::read(reader, key)); match xml_data.header_hash { Some(header_hash) => { if meta_data.header_hash != header_hash { return Err(Error::InvalidHeaderHash); } } None => {} } let db = Database { comment: meta_data.comment, composite_key: key.clone(), compression: meta_data.compression, db_type: DbType::Kdb2, master_cipher: meta_data.master_cipher, stream_cipher: meta_data.stream_cipher, transform_rounds: meta_data.transform_rounds, version: meta_data.version, binaries: xml_data.binaries, color: xml_data.color, custom_data: xml_data.custom_data, custom_icons: xml_data.custom_icons, def_username: xml_data.def_username, def_username_changed: xml_data.def_username_changed, description: xml_data.description, description_changed: xml_data.description_changed, entries: xml_data.entries, entry_templates_group_changed: xml_data.entry_templates_group_changed, entry_templates_group_uuid: xml_data.entry_templates_group_uuid, generator: xml_data.generator, group_uuid: xml_data.group_uuid, groups: xml_data.groups, history: xml_data.history, history_max_items: xml_data.history_max_items, history_max_size: xml_data.history_max_size, last_selected_group: xml_data.last_selected_group, last_top_visible_group: xml_data.last_top_visible_group, maintenance_history_days: xml_data.maintenance_history_days, master_key_change_force: xml_data.master_key_change_force, master_key_change_rec: xml_data.master_key_change_rec, master_key_changed: xml_data.master_key_changed, name: xml_data.name, name_changed: xml_data.name_changed, protect_notes: xml_data.protect_notes, protect_password: xml_data.protect_password, protect_title: xml_data.protect_title, protect_url: xml_data.protect_url, protect_username: xml_data.protect_username, recycle_bin_changed: xml_data.recycle_bin_changed, recycle_bin_enabled: xml_data.recycle_bin_enabled, recycle_bin_uuid: xml_data.recycle_bin_uuid, }; Ok(db) } } #[cfg(test)] mod tests { use chrono::{Duration, UTC}; use super::*; use types::BinariesMap; use types::CompositeKey; use types::Compression; use types::CustomDataMap; use types::CustomIconsMap; use types::DbType; use types::EntriesMap; use types::GroupUuid; use types::HistoryMap; use types::MasterCipher; use types::StreamCipher; use types::TransformRounds; use types::Version; #[test] fn test_new_returns_correct_instance() { let now = UTC::now(); let key = CompositeKey::from_password("5pZ5mgpTkLCDaM46IuH7yGafZFIICyvC"); let db = Database::new(&key); assert_eq!(db.comment, None); assert_eq!(db.composite_key, key); assert_eq!(db.compression, Compression::GZip); assert_eq!(db.db_type, DbType::Kdb2); assert_eq!(db.master_cipher, MasterCipher::Aes256); assert_eq!(db.stream_cipher, StreamCipher::Salsa20); assert_eq!(db.transform_rounds, TransformRounds(10000)); assert_eq!(db.version, Version::new_kdb2()); assert_eq!(db.binaries, BinariesMap::new()); assert_eq!(db.color, None); assert_eq!(db.custom_data, CustomDataMap::new()); assert_eq!(db.custom_icons, CustomIconsMap::new()); assert_eq!(db.def_username, ""); assert!((db.def_username_changed - now) < Duration::seconds(1)); assert_eq!(db.description, ""); assert!((db.description_changed - now) < Duration::seconds(1)); assert_eq!(db.entries, EntriesMap::new()); assert!((db.entry_templates_group_changed - now) < Duration::seconds(1)); assert_eq!(db.entry_templates_group_uuid, GroupUuid::nil()); assert_eq!(db.generator, "rust-kpdb"); assert!(db.group_uuid != None); assert!(db.group_uuid != Some(GroupUuid::nil())); assert_eq!(db.groups.len(), 2); assert_eq!(db.history, HistoryMap::new()); assert_eq!(db.history_max_items, 10); assert_eq!(db.history_max_size, 6291456); assert_eq!(db.last_selected_group, GroupUuid::nil()); assert_eq!(db.last_top_visible_group, GroupUuid::nil()); assert_eq!(db.maintenance_history_days, 365); assert_eq!(db.master_key_change_force, -1); assert_eq!(db.master_key_change_rec, -1); assert!((db.master_key_changed - now) < Duration::seconds(1)); assert_eq!(db.name, ""); assert!((db.name_changed - now) < Duration::seconds(1)); assert_eq!(db.protect_notes, false); assert_eq!(db.protect_password, true); assert_eq!(db.protect_title, false); assert_eq!(db.protect_url, false); assert_eq!(db.protect_username, false); assert!((db.recycle_bin_changed - now) < Duration::seconds(1)); assert_eq!(db.recycle_bin_enabled, true); assert!(db.recycle_bin_uuid != GroupUuid::nil()); } }
use chrono::{DateTime, UTC}; use common; use format::{kdb2_reader, kdb2_writer}; use io::{Log, LogReader, LogWriter}; use std::io::{Read, Write}; use super::binaries_map::BinariesMap; use super::color::Color; use super::comment::Comment; use super::composite_key::CompositeKey; use super::compression::Compression; use super::custom_data_map::CustomDataMap; use super::custom_icons_map::CustomIconsMap; use super::db_type::DbType; use super::entries_map::EntriesMap; use super::error::Error; use super::group::Group; use super::group_uuid::GroupUuid; use super::groups_map::GroupsMap; use super::history_map::HistoryMap; use super::icon::Icon; use super::master_cipher::MasterCipher; use super::result::Result; use super::stream_cipher::StreamCipher; use super::transform_rounds::TransformRounds; use super::version::Version; #[derive(Clone, Debug, PartialEq)] pub struct Database { pub comment: Option<Comment>, pub composite_key: CompositeKey, pub compression: Compression, pub db_type: DbType, pub master_cipher: MasterCipher, pub stream_cipher: StreamCipher, pub transform_rounds: TransformRounds, pub version: Version, pub binaries: BinariesMap, pub color: Option<Color>, pub custom_data: CustomDataMap, pub custom_icons: CustomIconsMap, pub def_username: String, pub def_username_changed: DateTime<UTC>, pub description: String, pub description_changed: DateTime<UTC>, pub entries: EntriesMap, pub entry_templates_group_changed: DateTime<UTC>, pub entry_templates_group_uuid: GroupUuid, pub generator: String, pub group_uuid: Option<GroupUuid>, pub groups: GroupsMap, pub history: HistoryMap, pub history_max_items: i32, pub history_max_size: i32, pub last_selected_group: GroupUuid, pub last_top_visible_group: GroupUuid, pub maintenance_history_days: i32, pub master_key_change_force: i32, pub master_key_change_rec: i32, pub master_key_changed: DateTime<UTC>, pub name: String, pub name_changed: DateTime<UTC>, pub protect_notes: bool, pub protect_password: bool, pub protect_title: bool, pub protect_url: bool, pub protect_username: bool, pub recycle_bin_changed: DateTime<UTC>, pub recycle_bin_enabled: bool, pub recycle_bin_uuid: GroupUuid, } impl Database { pub fn new(key: &CompositeKey) -> Database { let now = UTC::now(); let mut root = Group::new(common::ROOT_GROUP_NAME); let mut recycle_bin = Group::new(common::RECYCLE_BIN_NAME); let mut groups = GroupsMap::new(); recycle_bin.enable_auto_type = Some(false); recycle_bin.enable_searching = Some(false); recycle_bin.icon = Icon::RecycleBin; let root_uuid = root.uuid; let recycle_bin_uuid = recycle_bin.uuid; root.groups.push(recycle_bin_uuid); groups.insert(root_uuid, root); groups.insert(recycle_bin_uuid, recycle_bin); Database { comment: None, composite_key: key.clone(), compression: Compression::GZip, db_type: DbType::Kdb2, master_cipher: MasterCipher::Aes256, stream_cipher: StreamCipher::Salsa20, transform_rounds: TransformRounds(10000), version: Version::new_kdb2(), binaries: BinariesMap::new(), color: None, custom_data: CustomDataMap::new(), custom_icons: CustomIconsMap::new(), def_username: String::new(), def_username_changed: now, description: String::new(), description_changed: now, entries: EntriesMap::new(), entry_templates_group_changed: now, entry_templates_group_uuid: GroupUuid::nil(), generator: String::from(common::GENERATOR_NAME), group_uuid: Some(root_uuid), groups: groups, history: HistoryMap::new(), history_max_items: common::HISTORY_MAX_ITEMS_DEFAULT, history_max_size: common::HISTORY_MAX_SIZE_DEFAULT, last_selected_group: GroupUuid::nil(), last_top_visible_group: GroupUuid::nil(), maintenance_history_days: common::MAINTENANCE_HISTORY_DAYS_DEFAULT, master_key_change_force: common::MASTER_KEY_CHANGE_FORCE_DEFAULT, master_key_change_rec: common::MASTER_KEY_CHANGE_REC_DEFAULT, master_key_changed: now, name: String::new(), name_changed: now, protect_notes: common::PROTECT_NOTES_DEFAULT, protect_password: common::PROTECT_PASSWORD_DEFAULT, protect_title: common::PROTECT_TITLE_DEFAULT, protect_url: common::PROTECT_URL_DEFAULT, protect_username: common::PROTECT_USERNAME_DEFAULT, recycle_bin_changed: now, recycle_bin_enabled: common::RECYCLE_BIN_ENABLED_DEFAULT, recycle_bin_uuid: recycle_bin_uuid, } } pub fn open<R: Read>(reader: &mut R, key: &CompositeKey) -> Result<Database> { let mut reader = LogReader::new(reader); let mut buffer = [0u8; 4]; try!(reader.read(&mut buffer)); if buffer != common::DB_SIGNATURE { return Err(Error::InvalidDbSignature(buffer)); } try!(reader.read(&mut buffer)); if buffer == common::KDB1_SIGNATURE { return Err(Error::UnhandledDbType(buffer)); } else if buffer == common::KDB2_SIGNATURE { Database::open_kdb2(&mut reader, key) } else { return Err(Error::UnhandledDbType(buffer)); } } pub fn save<W: Write>(&self, writer: &mut W) -> Result<()> { let mut writer = LogWriter::new(writer);
} fn open_kdb2<R: Log + Read>(reader: &mut R, key: &CompositeKey) -> Result<Database> { let (meta_data, xml_data) = try!(kdb2_reader::read(reader, key)); match xml_data.header_hash { Some(header_hash) => { if meta_data.header_hash != header_hash { return Err(Error::InvalidHeaderHash); } } None => {} } let db = Database { comment: meta_data.comment, composite_key: key.clone(), compression: meta_data.compression, db_type: DbType::Kdb2, master_cipher: meta_data.master_cipher, stream_cipher: meta_data.stream_cipher, transform_rounds: meta_data.transform_rounds, version: meta_data.version, binaries: xml_data.binaries, color: xml_data.color, custom_data: xml_data.custom_data, custom_icons: xml_data.custom_icons, def_username: xml_data.def_username, def_username_changed: xml_data.def_username_changed, description: xml_data.description, description_changed: xml_data.description_changed, entries: xml_data.entries, entry_templates_group_changed: xml_data.entry_templates_group_changed, entry_templates_group_uuid: xml_data.entry_templates_group_uuid, generator: xml_data.generator, group_uuid: xml_data.group_uuid, groups: xml_data.groups, history: xml_data.history, history_max_items: xml_data.history_max_items, history_max_size: xml_data.history_max_size, last_selected_group: xml_data.last_selected_group, last_top_visible_group: xml_data.last_top_visible_group, maintenance_history_days: xml_data.maintenance_history_days, master_key_change_force: xml_data.master_key_change_force, master_key_change_rec: xml_data.master_key_change_rec, master_key_changed: xml_data.master_key_changed, name: xml_data.name, name_changed: xml_data.name_changed, protect_notes: xml_data.protect_notes, protect_password: xml_data.protect_password, protect_title: xml_data.protect_title, protect_url: xml_data.protect_url, protect_username: xml_data.protect_username, recycle_bin_changed: xml_data.recycle_bin_changed, recycle_bin_enabled: xml_data.recycle_bin_enabled, recycle_bin_uuid: xml_data.recycle_bin_uuid, }; Ok(db) } } #[cfg(test)] mod tests { use chrono::{Duration, UTC}; use super::*; use types::BinariesMap; use types::CompositeKey; use types::Compression; use types::CustomDataMap; use types::CustomIconsMap; use types::DbType; use types::EntriesMap; use types::GroupUuid; use types::HistoryMap; use types::MasterCipher; use types::StreamCipher; use types::TransformRounds; use types::Version; #[test] fn test_new_returns_correct_instance() { let now = UTC::now(); let key = CompositeKey::from_password("5pZ5mgpTkLCDaM46IuH7yGafZFIICyvC"); let db = Database::new(&key); assert_eq!(db.comment, None); assert_eq!(db.composite_key, key); assert_eq!(db.compression, Compression::GZip); assert_eq!(db.db_type, DbType::Kdb2); assert_eq!(db.master_cipher, MasterCipher::Aes256); assert_eq!(db.stream_cipher, StreamCipher::Salsa20); assert_eq!(db.transform_rounds, TransformRounds(10000)); assert_eq!(db.version, Version::new_kdb2()); assert_eq!(db.binaries, BinariesMap::new()); assert_eq!(db.color, None); assert_eq!(db.custom_data, CustomDataMap::new()); assert_eq!(db.custom_icons, CustomIconsMap::new()); assert_eq!(db.def_username, ""); assert!((db.def_username_changed - now) < Duration::seconds(1)); assert_eq!(db.description, ""); assert!((db.description_changed - now) < Duration::seconds(1)); assert_eq!(db.entries, EntriesMap::new()); assert!((db.entry_templates_group_changed - now) < Duration::seconds(1)); assert_eq!(db.entry_templates_group_uuid, GroupUuid::nil()); assert_eq!(db.generator, "rust-kpdb"); assert!(db.group_uuid != None); assert!(db.group_uuid != Some(GroupUuid::nil())); assert_eq!(db.groups.len(), 2); assert_eq!(db.history, HistoryMap::new()); assert_eq!(db.history_max_items, 10); assert_eq!(db.history_max_size, 6291456); assert_eq!(db.last_selected_group, GroupUuid::nil()); assert_eq!(db.last_top_visible_group, GroupUuid::nil()); assert_eq!(db.maintenance_history_days, 365); assert_eq!(db.master_key_change_force, -1); assert_eq!(db.master_key_change_rec, -1); assert!((db.master_key_changed - now) < Duration::seconds(1)); assert_eq!(db.name, ""); assert!((db.name_changed - now) < Duration::seconds(1)); assert_eq!(db.protect_notes, false); assert_eq!(db.protect_password, true); assert_eq!(db.protect_title, false); assert_eq!(db.protect_url, false); assert_eq!(db.protect_username, false); assert!((db.recycle_bin_changed - now) < Duration::seconds(1)); assert_eq!(db.recycle_bin_enabled, true); assert!(db.recycle_bin_uuid != GroupUuid::nil()); } }
match self.db_type { DbType::Kdb1 => Err(Error::Unimplemented(String::from("KeePass v1 not supported"))), DbType::Kdb2 => kdb2_writer::write(&mut writer, self), }
if_condition
[ { "content": "/// Attempts to write the key file to the writer.\n\npub fn write<W: Write>(writer: &mut W, key: &KeyFile) -> Result<()> {\n\n match key.file_type {\n\n KeyFileType::Binary => write_binary(writer, key),\n\n KeyFileType::Hex => write_hex(writer, key),\n\n KeyFileType::Xml =>...
Rust
crates/aingle_sqlite/src/db.rs
Daironode/aingle
54bfcbe21f587699a4e66e6764fe879a348987c8
use crate::{ conn::{new_connection_pool, ConnectionPool, PConn, DATABASE_HANDLES}, prelude::*, }; use derive_more::Into; use futures::Future; use ai_hash::SafHash; use aingle_zome_types::cell::CellId; use kitsune_p2p::KitsuneSpace; use parking_lot::Mutex; use rusqlite::*; use shrinkwraprs::Shrinkwrap; use std::path::PathBuf; use std::sync::Arc; use std::{collections::HashMap, path::Path}; use tokio::{ sync::{OwnedSemaphorePermit, Semaphore}, task, }; mod p2p_agent_store; pub use p2p_agent_store::*; mod p2p_metrics; pub use p2p_metrics::*; #[derive(Clone)] pub struct DbRead { kind: DbKind, path: PathBuf, connection_pool: ConnectionPool, write_semaphore: Arc<Semaphore>, read_semaphore: Arc<Semaphore>, } impl DbRead { pub fn conn(&self) -> DatabaseResult<PConn> { self.connection_pooled() } #[deprecated = "remove this identity function"] pub fn inner(&self) -> Self { self.clone() } pub fn kind(&self) -> &DbKind { &self.kind } pub fn path(&self) -> &PathBuf { &self.path } fn connection_pooled(&self) -> DatabaseResult<PConn> { let now = std::time::Instant::now(); let r = Ok(PConn::new(self.connection_pool.get()?, self.kind.clone())); let el = now.elapsed(); if el.as_millis() > 20 { tracing::error!("Connection pool took {:?} to be free'd", el); } r } } #[derive(Clone, Shrinkwrap, Into, derive_more::From)] pub struct DbWrite(DbRead); impl DbWrite { pub fn open(path_prefix: &Path, kind: DbKind) -> DatabaseResult<DbWrite> { let path = path_prefix.join(kind.filename()); if let Some(v) = DATABASE_HANDLES.get(&path) { Ok(v.clone()) } else { let db = Self::new(path_prefix, kind)?; DATABASE_HANDLES.insert_new(path, db.clone()); Ok(db) } } pub(crate) fn new(path_prefix: &Path, kind: DbKind) -> DatabaseResult<Self> { let path = path_prefix.join(kind.filename()); let parent = path .parent() .ok_or_else(|| DatabaseError::DatabaseMissing(path_prefix.to_owned()))?; if !parent.is_dir() { std::fs::create_dir_all(parent) .map_err(|_e| DatabaseError::DatabaseMissing(parent.to_owned()))?; } let pool = new_connection_pool(&path, kind.clone()); let mut conn = pool.get()?; crate::table::initialize_database(&mut conn, &kind)?; Ok(DbWrite(DbRead { write_semaphore: Self::get_write_semaphore(&kind), read_semaphore: Self::get_read_semaphore(&kind), kind, path, connection_pool: pool, })) } fn get_write_semaphore(kind: &DbKind) -> Arc<Semaphore> { static MAP: once_cell::sync::Lazy<Mutex<HashMap<DbKind, Arc<Semaphore>>>> = once_cell::sync::Lazy::new(|| Mutex::new(HashMap::new())); let mut map = MAP.lock(); match map.get(kind) { Some(s) => s.clone(), None => { let s = Arc::new(Semaphore::new(1)); map.insert(kind.clone(), s.clone()); s } } } fn get_read_semaphore(kind: &DbKind) -> Arc<Semaphore> { static MAP: once_cell::sync::Lazy<Mutex<HashMap<DbKind, Arc<Semaphore>>>> = once_cell::sync::Lazy::new(|| Mutex::new(HashMap::new())); let mut map = MAP.lock(); match map.get(kind) { Some(s) => s.clone(), None => { let num_cpus = num_cpus::get(); let num_read_threads = if num_cpus < 4 { 4 } else { num_cpus / 2 }; let s = Arc::new(Semaphore::new(num_read_threads)); map.insert(kind.clone(), s.clone()); s } } } #[cfg(any(test, feature = "test_utils"))] pub fn test(tmpdir: &tempdir::TempDir, kind: DbKind) -> DatabaseResult<Self> { Self::new(tmpdir.path(), kind) } #[deprecated = "is this used?"] pub async fn remove(self) -> DatabaseResult<()> { if let Some(parent) = self.0.path.parent() { std::fs::remove_dir_all(parent)?; } Ok(()) } } #[derive(Clone, Debug, PartialEq, Eq, Hash, derive_more::Display)] pub enum DbKind { Cell(CellId), Cache(SafHash), Conductor, Wasm, P2pAgentStore(Arc<KitsuneSpace>), P2pMetrics(Arc<KitsuneSpace>), } impl DbKind { fn filename(&self) -> PathBuf { let mut path: PathBuf = match self { DbKind::Cell(cell_id) => ["cell", &cell_id.to_string()].iter().collect(), DbKind::Cache(saf) => ["cache", &format!("cache-{}", saf)].iter().collect(), DbKind::Conductor => ["conductor", "conductor"].iter().collect(), DbKind::Wasm => ["wasm", "wasm"].iter().collect(), DbKind::P2pAgentStore(space) => ["p2p", &format!("p2p_agent_store-{}", space)] .iter() .collect(), DbKind::P2pMetrics(space) => { ["p2p", &format!("p2p_metrics-{}", space)].iter().collect() } }; path.set_extension("sqlite3"); path } } pub trait ReadManager<'e> { fn with_reader<E, R, F>(&'e mut self, f: F) -> Result<R, E> where E: From<DatabaseError>, F: 'e + FnOnce(Transaction) -> Result<R, E>; #[cfg(feature = "test_utils")] fn with_reader_test<R, F>(&'e mut self, f: F) -> R where F: 'e + FnOnce(Transaction) -> R; } pub trait WriteManager<'e> { #[cfg(feature = "test_utils")] fn with_commit_sync<E, R, F>(&'e mut self, f: F) -> Result<R, E> where E: From<DatabaseError>, F: 'e + FnOnce(&mut Transaction) -> Result<R, E>; #[cfg(feature = "test_utils")] fn with_commit_test<R, F>(&'e mut self, f: F) -> Result<R, DatabaseError> where F: 'e + FnOnce(&mut Transaction) -> R, { self.with_commit_sync(|w| DatabaseResult::Ok(f(w))) } } impl<'e> ReadManager<'e> for PConn { fn with_reader<E, R, F>(&'e mut self, f: F) -> Result<R, E> where E: From<DatabaseError>, F: 'e + FnOnce(Transaction) -> Result<R, E>, { let txn = self.transaction().map_err(DatabaseError::from)?; f(txn) } #[cfg(feature = "test_utils")] fn with_reader_test<R, F>(&'e mut self, f: F) -> R where F: 'e + FnOnce(Transaction) -> R, { self.with_reader(|r| DatabaseResult::Ok(f(r))).unwrap() } } impl DbRead { pub async fn async_reader<E, R, F>(&self, f: F) -> Result<R, E> where E: From<DatabaseError> + Send + 'static, F: FnOnce(Transaction) -> Result<R, E> + Send + 'static, R: Send + 'static, { let _g = self.acquire_reader_permit().await; let mut conn = self.conn()?; let r = task::spawn_blocking(move || conn.with_reader(f)) .await .map_err(DatabaseError::from)?; r } async fn acquire_reader_permit(&self) -> OwnedSemaphorePermit { self.read_semaphore .clone() .acquire_owned() .await .expect("We don't ever close these semaphores") } } impl<'e> WriteManager<'e> for PConn { #[cfg(feature = "test_utils")] fn with_commit_sync<E, R, F>(&'e mut self, f: F) -> Result<R, E> where E: From<DatabaseError>, F: 'e + FnOnce(&mut Transaction) -> Result<R, E>, { let mut txn = self .transaction_with_behavior(TransactionBehavior::Exclusive) .map_err(DatabaseError::from)?; let result = f(&mut txn)?; txn.commit().map_err(DatabaseError::from)?; Ok(result) } } impl DbWrite { pub async fn async_commit<E, R, F>(&self, f: F) -> Result<R, E> where E: From<DatabaseError> + Send + 'static, F: FnOnce(&mut Transaction) -> Result<R, E> + Send + 'static, R: Send + 'static, { let _g = self.acquire_writer_permit().await; let mut conn = self.conn()?; let r = task::spawn_blocking(move || conn.with_commit_sync(f)) .await .map_err(DatabaseError::from)?; r } pub async fn async_commit_in_place<E, R, F>(&self, f: F) -> Result<R, E> where E: From<DatabaseError>, F: FnOnce(&mut Transaction) -> Result<R, E>, R: Send, { let _g = self.acquire_writer_permit().await; let mut conn = self.conn()?; task::block_in_place(move || conn.with_commit_sync(f)) } async fn acquire_writer_permit(&self) -> OwnedSemaphorePermit { self.0 .write_semaphore .clone() .acquire_owned() .await .expect("We don't ever close these semaphores") } } #[derive(Debug)] pub struct OptimisticRetryError<E: std::error::Error>(Vec<E>); impl<E: std::error::Error> std::fmt::Display for OptimisticRetryError<E> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { writeln!( f, "OptimisticRetryError had too many failures:\n{:#?}", self.0 ) } } impl<E: std::error::Error> std::error::Error for OptimisticRetryError<E> {} pub async fn optimistic_retry_async<Func, Fut, T, E>( ctx: &str, mut f: Func, ) -> Result<T, OptimisticRetryError<E>> where Func: FnMut() -> Fut, Fut: Future<Output = Result<T, E>>, E: std::error::Error, { use tokio::time::Duration; const NUM_CONSECUTIVE_FAILURES: usize = 10; const RETRY_INTERVAL: Duration = Duration::from_millis(500); let mut errors = Vec::new(); loop { match f().await { Ok(x) => return Ok(x), Err(err) => { tracing::error!( "Error during optimistic_retry. Failures: {}/{}. Context: {}. Error: {:?}", errors.len() + 1, NUM_CONSECUTIVE_FAILURES, ctx, err ); errors.push(err); if errors.len() >= NUM_CONSECUTIVE_FAILURES { return Err(OptimisticRetryError(errors)); } } } tokio::time::sleep(RETRY_INTERVAL).await; } }
use crate::{ conn::{new_connection_pool, ConnectionPool, PConn, DATABASE_HANDLES}, prelude::*, }; use derive_more::Into; use futures::Future; use ai_hash::SafHash; use aingle_zome_types::cell::CellId; use kitsune_p2p::KitsuneSpace; use parking_lot::Mutex; use rusqlite::*; use shrinkwraprs::Shrinkwrap; use std::path::PathBuf; use std::sync::Arc; use std::{collections::HashMap, path::Path}; use tokio::{ sync::{OwnedSemaphorePermit, Semaphore}, task, }; mod p2p_agent_store; pub use p2p_agent_store::*; mod p2p_metrics; pub use p2p_metrics::*; #[derive(Clone)] pub struct DbRead { kind: DbKind, path: PathBuf, connection_pool: ConnectionPool, write_semaphore: Arc<Semaphore>, read_semaphore: Arc<Semaphore>, } impl DbRead { pub fn conn(&self) -> DatabaseResult<PConn> { self.connection_pooled() } #[deprecated = "remove this identity function"] pub fn inner(&self) -> Self { self.clone() } pub fn kind(&self) -> &DbKind { &self.kind } pub fn path(&self) -> &PathBuf { &self.path } fn connection_pooled(&self) -> DatabaseResult<PConn> { let now = std::time::Instant::now(); let r = Ok(PConn::new(self.connection_pool.get()?, self.kind.clone())); let el = now.elapsed(); if el.as_millis() > 20 { tracing::error!("Connection pool took {:?} to be free'd", el); } r } } #[derive(Clone, Shrinkwrap, Into, derive_more::From)] pub struct DbWrite(DbRead); impl DbWrite { pub fn open(path_prefix: &Path, kind: DbKind) -> DatabaseResult<DbWrite> { let path = path_prefix.join(kind.filename()); if let Some(v) = DATABASE_HANDLES.get(&path) { Ok(v.clone()) } else { let db = Self::new(path_prefix, kind)?; DATABASE_HANDLES.insert_new(path, db.clone()); Ok(db) } }
fn get_write_semaphore(kind: &DbKind) -> Arc<Semaphore> { static MAP: once_cell::sync::Lazy<Mutex<HashMap<DbKind, Arc<Semaphore>>>> = once_cell::sync::Lazy::new(|| Mutex::new(HashMap::new())); let mut map = MAP.lock(); match map.get(kind) { Some(s) => s.clone(), None => { let s = Arc::new(Semaphore::new(1)); map.insert(kind.clone(), s.clone()); s } } } fn get_read_semaphore(kind: &DbKind) -> Arc<Semaphore> { static MAP: once_cell::sync::Lazy<Mutex<HashMap<DbKind, Arc<Semaphore>>>> = once_cell::sync::Lazy::new(|| Mutex::new(HashMap::new())); let mut map = MAP.lock(); match map.get(kind) { Some(s) => s.clone(), None => { let num_cpus = num_cpus::get(); let num_read_threads = if num_cpus < 4 { 4 } else { num_cpus / 2 }; let s = Arc::new(Semaphore::new(num_read_threads)); map.insert(kind.clone(), s.clone()); s } } } #[cfg(any(test, feature = "test_utils"))] pub fn test(tmpdir: &tempdir::TempDir, kind: DbKind) -> DatabaseResult<Self> { Self::new(tmpdir.path(), kind) } #[deprecated = "is this used?"] pub async fn remove(self) -> DatabaseResult<()> { if let Some(parent) = self.0.path.parent() { std::fs::remove_dir_all(parent)?; } Ok(()) } } #[derive(Clone, Debug, PartialEq, Eq, Hash, derive_more::Display)] pub enum DbKind { Cell(CellId), Cache(SafHash), Conductor, Wasm, P2pAgentStore(Arc<KitsuneSpace>), P2pMetrics(Arc<KitsuneSpace>), } impl DbKind { fn filename(&self) -> PathBuf { let mut path: PathBuf = match self { DbKind::Cell(cell_id) => ["cell", &cell_id.to_string()].iter().collect(), DbKind::Cache(saf) => ["cache", &format!("cache-{}", saf)].iter().collect(), DbKind::Conductor => ["conductor", "conductor"].iter().collect(), DbKind::Wasm => ["wasm", "wasm"].iter().collect(), DbKind::P2pAgentStore(space) => ["p2p", &format!("p2p_agent_store-{}", space)] .iter() .collect(), DbKind::P2pMetrics(space) => { ["p2p", &format!("p2p_metrics-{}", space)].iter().collect() } }; path.set_extension("sqlite3"); path } } pub trait ReadManager<'e> { fn with_reader<E, R, F>(&'e mut self, f: F) -> Result<R, E> where E: From<DatabaseError>, F: 'e + FnOnce(Transaction) -> Result<R, E>; #[cfg(feature = "test_utils")] fn with_reader_test<R, F>(&'e mut self, f: F) -> R where F: 'e + FnOnce(Transaction) -> R; } pub trait WriteManager<'e> { #[cfg(feature = "test_utils")] fn with_commit_sync<E, R, F>(&'e mut self, f: F) -> Result<R, E> where E: From<DatabaseError>, F: 'e + FnOnce(&mut Transaction) -> Result<R, E>; #[cfg(feature = "test_utils")] fn with_commit_test<R, F>(&'e mut self, f: F) -> Result<R, DatabaseError> where F: 'e + FnOnce(&mut Transaction) -> R, { self.with_commit_sync(|w| DatabaseResult::Ok(f(w))) } } impl<'e> ReadManager<'e> for PConn { fn with_reader<E, R, F>(&'e mut self, f: F) -> Result<R, E> where E: From<DatabaseError>, F: 'e + FnOnce(Transaction) -> Result<R, E>, { let txn = self.transaction().map_err(DatabaseError::from)?; f(txn) } #[cfg(feature = "test_utils")] fn with_reader_test<R, F>(&'e mut self, f: F) -> R where F: 'e + FnOnce(Transaction) -> R, { self.with_reader(|r| DatabaseResult::Ok(f(r))).unwrap() } } impl DbRead { pub async fn async_reader<E, R, F>(&self, f: F) -> Result<R, E> where E: From<DatabaseError> + Send + 'static, F: FnOnce(Transaction) -> Result<R, E> + Send + 'static, R: Send + 'static, { let _g = self.acquire_reader_permit().await; let mut conn = self.conn()?; let r = task::spawn_blocking(move || conn.with_reader(f)) .await .map_err(DatabaseError::from)?; r } async fn acquire_reader_permit(&self) -> OwnedSemaphorePermit { self.read_semaphore .clone() .acquire_owned() .await .expect("We don't ever close these semaphores") } } impl<'e> WriteManager<'e> for PConn { #[cfg(feature = "test_utils")] fn with_commit_sync<E, R, F>(&'e mut self, f: F) -> Result<R, E> where E: From<DatabaseError>, F: 'e + FnOnce(&mut Transaction) -> Result<R, E>, { let mut txn = self .transaction_with_behavior(TransactionBehavior::Exclusive) .map_err(DatabaseError::from)?; let result = f(&mut txn)?; txn.commit().map_err(DatabaseError::from)?; Ok(result) } } impl DbWrite { pub async fn async_commit<E, R, F>(&self, f: F) -> Result<R, E> where E: From<DatabaseError> + Send + 'static, F: FnOnce(&mut Transaction) -> Result<R, E> + Send + 'static, R: Send + 'static, { let _g = self.acquire_writer_permit().await; let mut conn = self.conn()?; let r = task::spawn_blocking(move || conn.with_commit_sync(f)) .await .map_err(DatabaseError::from)?; r } pub async fn async_commit_in_place<E, R, F>(&self, f: F) -> Result<R, E> where E: From<DatabaseError>, F: FnOnce(&mut Transaction) -> Result<R, E>, R: Send, { let _g = self.acquire_writer_permit().await; let mut conn = self.conn()?; task::block_in_place(move || conn.with_commit_sync(f)) } async fn acquire_writer_permit(&self) -> OwnedSemaphorePermit { self.0 .write_semaphore .clone() .acquire_owned() .await .expect("We don't ever close these semaphores") } } #[derive(Debug)] pub struct OptimisticRetryError<E: std::error::Error>(Vec<E>); impl<E: std::error::Error> std::fmt::Display for OptimisticRetryError<E> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { writeln!( f, "OptimisticRetryError had too many failures:\n{:#?}", self.0 ) } } impl<E: std::error::Error> std::error::Error for OptimisticRetryError<E> {} pub async fn optimistic_retry_async<Func, Fut, T, E>( ctx: &str, mut f: Func, ) -> Result<T, OptimisticRetryError<E>> where Func: FnMut() -> Fut, Fut: Future<Output = Result<T, E>>, E: std::error::Error, { use tokio::time::Duration; const NUM_CONSECUTIVE_FAILURES: usize = 10; const RETRY_INTERVAL: Duration = Duration::from_millis(500); let mut errors = Vec::new(); loop { match f().await { Ok(x) => return Ok(x), Err(err) => { tracing::error!( "Error during optimistic_retry. Failures: {}/{}. Context: {}. Error: {:?}", errors.len() + 1, NUM_CONSECUTIVE_FAILURES, ctx, err ); errors.push(err); if errors.len() >= NUM_CONSECUTIVE_FAILURES { return Err(OptimisticRetryError(errors)); } } } tokio::time::sleep(RETRY_INTERVAL).await; } }
pub(crate) fn new(path_prefix: &Path, kind: DbKind) -> DatabaseResult<Self> { let path = path_prefix.join(kind.filename()); let parent = path .parent() .ok_or_else(|| DatabaseError::DatabaseMissing(path_prefix.to_owned()))?; if !parent.is_dir() { std::fs::create_dir_all(parent) .map_err(|_e| DatabaseError::DatabaseMissing(parent.to_owned()))?; } let pool = new_connection_pool(&path, kind.clone()); let mut conn = pool.get()?; crate::table::initialize_database(&mut conn, &kind)?; Ok(DbWrite(DbRead { write_semaphore: Self::get_write_semaphore(&kind), read_semaphore: Self::get_read_semaphore(&kind), kind, path, connection_pool: pool, })) }
function_block-full_function
[ { "content": "/// Handle the result of shutting down the main thread.\n\npub fn handle_shutdown(result: Result<TaskManagerResult, tokio::task::JoinError>) {\n\n let result = result.map_err(|e| {\n\n error!(\n\n error = &e as &dyn std::error::Error,\n\n \"Failed to join the main t...
Rust
parity-ethereum/ethcore/pod/src/state.rs
wgr523/prism-smart-contracts
867167e5dea286f1616a9f192e751758e0c2606e
use std::collections::BTreeMap; use ethereum_types::{H256, Address}; use triehash::sec_trie_root; use common_types::state_diff::StateDiff; use ethjson; use serde::Serialize; use crate::account::PodAccount; #[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)] pub struct PodState(BTreeMap<Address, PodAccount>); impl PodState { pub fn get(&self) -> &BTreeMap<Address, PodAccount> { &self.0 } pub fn root(&self) -> H256 { sec_trie_root(self.0.iter().map(|(k, v)| (k, v.rlp()))) } pub fn drain(self) -> BTreeMap<Address, PodAccount> { self.0 } } impl From<ethjson::spec::State> for PodState { fn from(s: ethjson::spec::State) -> PodState { let state: BTreeMap<_,_> = s.into_iter() .filter(|pair| !pair.1.is_empty()) .map(|(addr, acc)| (addr.into(), PodAccount::from(acc))) .collect(); PodState(state) } } impl From<BTreeMap<Address, PodAccount>> for PodState { fn from(s: BTreeMap<Address, PodAccount>) -> Self { PodState(s) } } pub fn diff_pod(pre: &PodState, post: &PodState) -> StateDiff { StateDiff { raw: pre.0.keys() .chain(post.0.keys()) .filter_map(|acc| crate::account::diff_pod(pre.0.get(acc), post.0.get(acc)).map(|d| (*acc, d))) .collect() } } #[cfg(test)] mod test { use std::collections::BTreeMap; use common_types::{ account_diff::{AccountDiff, Diff}, state_diff::StateDiff, }; use ethereum_types::Address; use crate::account::PodAccount; use super::PodState; use macros::map; #[test] fn create_delete() { let a = PodState::from(map![ Address::from_low_u64_be(1) => PodAccount { balance: 69.into(), nonce: 0.into(), code: Some(Vec::new()), storage: map![], version: 0.into(), } ]); assert_eq!(super::diff_pod(&a, &PodState::default()), StateDiff { raw: map![ Address::from_low_u64_be(1) => AccountDiff{ balance: Diff::Died(69.into()), nonce: Diff::Died(0.into()), code: Diff::Died(vec![]), storage: map![], } ]}); assert_eq!(super::diff_pod(&PodState::default(), &a), StateDiff { raw: map![ Address::from_low_u64_be(1) => AccountDiff{ balance: Diff::Born(69.into()), nonce: Diff::Born(0.into()), code: Diff::Born(vec![]), storage: map![], } ]}); } #[test] fn create_delete_with_unchanged() { let a = PodState::from(map![ Address::from_low_u64_be(1) => PodAccount { balance: 69.into(), nonce: 0.into(), code: Some(Vec::new()), storage: map![], version: 0.into(), } ]); let b = PodState::from(map![ Address::from_low_u64_be(1) => PodAccount { balance: 69.into(), nonce: 0.into(), code: Some(Vec::new()), storage: map![], version: 0.into(), }, Address::from_low_u64_be(2) => PodAccount { balance: 69.into(), nonce: 0.into(), code: Some(Vec::new()), storage: map![], version: 0.into(), } ]); assert_eq!(super::diff_pod(&a, &b), StateDiff { raw: map![ Address::from_low_u64_be(2) => AccountDiff { balance: Diff::Born(69.into()), nonce: Diff::Born(0.into()), code: Diff::Born(vec![]), storage: map![], } ]}); assert_eq!(super::diff_pod(&b, &a), StateDiff { raw: map![ Address::from_low_u64_be(2) => AccountDiff { balance: Diff::Died(69.into()), nonce: Diff::Died(0.into()), code: Diff::Died(vec![]), storage: map![], } ]}); } #[test] fn change_with_unchanged() { let a = PodState::from(map![ Address::from_low_u64_be(1) => PodAccount { balance: 69.into(), nonce: 0.into(), code: Some(Vec::new()), storage: map![], version: 0.into(), }, Address::from_low_u64_be(2) => PodAccount { balance: 69.into(), nonce: 0.into(), code: Some(Vec::new()), storage: map![], version: 0.into(), } ]); let b = PodState::from(map![ Address::from_low_u64_be(1) => PodAccount { balance: 69.into(), nonce: 1.into(), code: Some(Vec::new()), storage: map![], version: 0.into(), }, Address::from_low_u64_be(2) => PodAccount { balance: 69.into(), nonce: 0.into(), code: Some(Vec::new()), storage: map![], version: 0.into(), } ]); assert_eq!(super::diff_pod(&a, &b), StateDiff { raw: map![ Address::from_low_u64_be(1) => AccountDiff { balance: Diff::Same, nonce: Diff::Changed(0.into(), 1.into()), code: Diff::Same, storage: map![], } ]}); } }
use std::collections::BTreeMap; use ethereum_types::{H256, Address}; use triehash::sec_trie_root; use common_types::state_diff::StateDiff; use ethjson; use serde::Serialize; use crate::account::PodAccount; #[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)] pub struct PodState(BTreeMap<Address, PodAccount>); impl PodState { pub fn get(&self) -> &BTreeMap<Address, PodAccount> { &self.0 } pub fn root(&self) -> H256 { sec_trie_root(self.0.iter().map(|(k, v)| (k, v.rlp()))) } pub fn drain(self) -> BTreeMap<Address, PodAccount> { self.0 } } impl From<ethjson::spec::State> for PodState { fn from(s: ethjson::spec::State) -> PodState { let state: BTreeMap<_,_> = s.into_iter() .filter(|pair| !pair.1.is_empty()) .map(|(addr, acc)| (addr.into(), PodAccount::from(acc))) .collect(); PodState(state) } } impl From<BTreeMap<Address, PodAccount>> for PodState { fn from(s: BTreeMap<Address, PodAccount>) -> Self { PodState(s) } } pub fn diff_pod(pre: &PodState, post: &PodState) -> StateDiff { StateDiff { raw: pre.0.keys() .chain(post.0.keys()) .filter_map(|acc| crate::account::diff_pod(pre.0.get(acc), post.0.get(acc)).map(|d| (*acc, d))) .collect() } } #[cfg(test)] mod test { use std::collections::BTreeMap; use common_types::{ account_diff::{AccountDiff, Diff}, state_diff::StateDiff, }; use ethereum_types::Address; use crate::account::PodAccount; use super::PodState; use macros::map; #[test] fn create_delete() {
#[test] fn create_delete_with_unchanged() { let a = PodState::from(map![ Address::from_low_u64_be(1) => PodAccount { balance: 69.into(), nonce: 0.into(), code: Some(Vec::new()), storage: map![], version: 0.into(), } ]); let b = PodState::from(map![ Address::from_low_u64_be(1) => PodAccount { balance: 69.into(), nonce: 0.into(), code: Some(Vec::new()), storage: map![], version: 0.into(), }, Address::from_low_u64_be(2) => PodAccount { balance: 69.into(), nonce: 0.into(), code: Some(Vec::new()), storage: map![], version: 0.into(), } ]); assert_eq!(super::diff_pod(&a, &b), StateDiff { raw: map![ Address::from_low_u64_be(2) => AccountDiff { balance: Diff::Born(69.into()), nonce: Diff::Born(0.into()), code: Diff::Born(vec![]), storage: map![], } ]}); assert_eq!(super::diff_pod(&b, &a), StateDiff { raw: map![ Address::from_low_u64_be(2) => AccountDiff { balance: Diff::Died(69.into()), nonce: Diff::Died(0.into()), code: Diff::Died(vec![]), storage: map![], } ]}); } #[test] fn change_with_unchanged() { let a = PodState::from(map![ Address::from_low_u64_be(1) => PodAccount { balance: 69.into(), nonce: 0.into(), code: Some(Vec::new()), storage: map![], version: 0.into(), }, Address::from_low_u64_be(2) => PodAccount { balance: 69.into(), nonce: 0.into(), code: Some(Vec::new()), storage: map![], version: 0.into(), } ]); let b = PodState::from(map![ Address::from_low_u64_be(1) => PodAccount { balance: 69.into(), nonce: 1.into(), code: Some(Vec::new()), storage: map![], version: 0.into(), }, Address::from_low_u64_be(2) => PodAccount { balance: 69.into(), nonce: 0.into(), code: Some(Vec::new()), storage: map![], version: 0.into(), } ]); assert_eq!(super::diff_pod(&a, &b), StateDiff { raw: map![ Address::from_low_u64_be(1) => AccountDiff { balance: Diff::Same, nonce: Diff::Changed(0.into(), 1.into()), code: Diff::Same, storage: map![], } ]}); } }
let a = PodState::from(map![ Address::from_low_u64_be(1) => PodAccount { balance: 69.into(), nonce: 0.into(), code: Some(Vec::new()), storage: map![], version: 0.into(), } ]); assert_eq!(super::diff_pod(&a, &PodState::default()), StateDiff { raw: map![ Address::from_low_u64_be(1) => AccountDiff{ balance: Diff::Died(69.into()), nonce: Diff::Died(0.into()), code: Diff::Died(vec![]), storage: map![], } ]}); assert_eq!(super::diff_pod(&PodState::default(), &a), StateDiff { raw: map![ Address::from_low_u64_be(1) => AccountDiff{ balance: Diff::Born(69.into()), nonce: Diff::Born(0.into()), code: Diff::Born(vec![]), storage: map![], } ]}); }
function_block-function_prefix_line
[ { "content": "/// Generates a trie root hash for a vector of key-value tuples\n\npub fn trie_root<I, K, V>(input: I) -> H256\n\nwhere\n\n I: IntoIterator<Item = (K, V)>,\n\n K: AsRef<[u8]> + Ord,\n\n V: AsRef<[u8]>,\n\n{\n\n triehash::trie_root::<KeccakHasher, _, _, _>(input)\n\n}\n\n\n", "file_...
Rust
fixed-price-sale/program/tests/create_store.rs
jarry-xiao/metaplex-program-library
ddb247622dcfd7501f6811007fbbb88b1bce1483
mod utils; #[cfg(feature = "test-bpf")] mod create_store { use crate::{setup_context, utils::helpers::airdrop}; use anchor_client::solana_sdk::{signature::Keypair, signer::Signer, system_program}; use anchor_lang::{AccountDeserialize, InstructionData, ToAccountMetas}; use mpl_fixed_price_sale::utils::puffed_out_string; use mpl_fixed_price_sale::{ accounts as mpl_fixed_price_sale_accounts, instruction as mpl_fixed_price_sale_instruction, state::Store, utils::{DESCRIPTION_MAX_LEN, NAME_MAX_LEN}, }; use solana_program::instruction::Instruction; use solana_program_test::*; use solana_sdk::{transaction::Transaction, transport::TransportError}; #[tokio::test] async fn success() { setup_context!(context, mpl_fixed_price_sale); let admin_wallet = Keypair::new(); let store_keypair = Keypair::new(); airdrop(&mut context, &admin_wallet.pubkey(), 10_000_000_000).await; let name = String::from("123456789_123456789_"); let description = String::from("123456789_123456789_123456789_"); let accounts = mpl_fixed_price_sale_accounts::CreateStore { admin: admin_wallet.pubkey(), store: store_keypair.pubkey(), system_program: system_program::id(), } .to_account_metas(None); let data = mpl_fixed_price_sale_instruction::CreateStore { name: name.to_owned(), description: description.to_owned(), } .data(); let instruction = Instruction { program_id: mpl_fixed_price_sale::id(), data, accounts, }; let tx = Transaction::new_signed_with_payer( &[instruction], Some(&context.payer.pubkey()), &[&context.payer, &admin_wallet, &store_keypair], context.last_blockhash, ); context.banks_client.process_transaction(tx).await.unwrap(); let store_acc = context .banks_client .get_account(store_keypair.pubkey()) .await .expect("account not found") .expect("account empty"); let store_data = Store::try_deserialize(&mut store_acc.data.as_ref()).unwrap(); assert_eq!(admin_wallet.pubkey(), store_data.admin); assert_eq!(puffed_out_string(name, NAME_MAX_LEN), store_data.name); assert_eq!( puffed_out_string(description, DESCRIPTION_MAX_LEN), store_data.description ); } #[tokio::test] async fn failure_name_is_long() { setup_context!(context, mpl_fixed_price_sale); let admin_wallet = Keypair::new(); let store_keypair = Keypair::new(); airdrop(&mut context, &admin_wallet.pubkey(), 10_000_000_000).await; let name = String::from("123456789_123456789_123456789_123456789_1"); let description = String::from("123456789_123456789_"); let accounts = mpl_fixed_price_sale_accounts::CreateStore { admin: admin_wallet.pubkey(), store: store_keypair.pubkey(), system_program: system_program::id(), } .to_account_metas(None); let data = mpl_fixed_price_sale_instruction::CreateStore { name: name.to_owned(), description: description.to_owned(), } .data(); let instruction = Instruction { program_id: mpl_fixed_price_sale::id(), data, accounts, }; let tx = Transaction::new_signed_with_payer( &[instruction], Some(&context.payer.pubkey()), &[&context.payer, &admin_wallet, &store_keypair], context.last_blockhash, ); let tx_result = context.banks_client.process_transaction(tx).await; match tx_result.unwrap_err() { TransportError::Custom(_) => assert!(true), TransportError::TransactionError(_) => assert!(true), _ => assert!(false), } } #[tokio::test] async fn failure_description_is_long() { setup_context!(context, mpl_fixed_price_sale); let admin_wallet = Keypair::new(); let store_keypair = Keypair::new(); airdrop(&mut context, &admin_wallet.pubkey(), 10_000_000_000).await; let name = String::from("123456789_123456789_"); let description = String::from("123456789_123456789_123456789_123456789_123456789_123456789_1"); let accounts = mpl_fixed_price_sale_accounts::CreateStore { admin: admin_wallet.pubkey(), store: store_keypair.pubkey(), system_program: system_program::id(), } .to_account_metas(None); let data = mpl_fixed_price_sale_instruction::CreateStore { name: name.to_owned(), description: description.to_owned(), } .data(); let instruction = Instruction { program_id: mpl_fixed_price_sale::id(), data, accounts, }; let tx = Transaction::new_signed_with_payer( &[instruction], Some(&context.payer.pubkey()), &[&context.payer, &admin_wallet, &store_keypair], context.last_blockhash, ); let tx_result = context.banks_client.process_transaction(tx).await; match tx_result.unwrap_err() { TransportError::Custom(_) => assert!(true), TransportError::TransactionError(_) => assert!(true), _ => assert!(false), } } #[tokio::test] #[should_panic] async fn failure_signer_is_missed() { setup_context!(context, mpl_fixed_price_sale); let admin_wallet = Keypair::new(); let store_keypair = Keypair::new(); airdrop(&mut context, &admin_wallet.pubkey(), 10_000_000_000).await; let name = String::from("123456789_123456789_"); let description = String::from("123456789_123456789_"); let accounts = mpl_fixed_price_sale_accounts::CreateStore { admin: admin_wallet.pubkey(), store: store_keypair.pubkey(), system_program: system_program::id(), } .to_account_metas(None); let data = mpl_fixed_price_sale_instruction::CreateStore { name: name.to_owned(), description: description.to_owned(), } .data(); let instruction = Instruction { program_id: mpl_fixed_price_sale::id(), data, accounts, }; let tx = Transaction::new_signed_with_payer( &[instruction], Some(&context.payer.pubkey()), &[&context.payer, &admin_wallet], context.last_blockhash, ); context.banks_client.process_transaction(tx).await.unwrap(); } }
mod utils; #[cfg(feature = "test-bpf")] mod create_store { use crate::{setup_context, utils::helpers::airdrop}; use anchor_client::solana_sdk::{signature::Keypair, signer::Signer, system_program}; use anchor_lang::{AccountDeserialize, InstructionData, ToAccountMetas}; use mpl_fixed_price_sale::utils::puffed_out_string; use mpl_fixed_price_sale::{ accounts as mpl_fixed_price_sale_accounts, instruction as mpl_fixed_price_sale_instruction, state::Store, utils::{DESCRIPTION_MAX_LEN, NAME_MAX_LEN}, }; use solana_program::instruction::Instruction; use solana_program_test::*; use solana_sdk::{transaction::Transaction, transport::TransportError}; #[tokio::test]
#[tokio::test] async fn failure_name_is_long() { setup_context!(context, mpl_fixed_price_sale); let admin_wallet = Keypair::new(); let store_keypair = Keypair::new(); airdrop(&mut context, &admin_wallet.pubkey(), 10_000_000_000).await; let name = String::from("123456789_123456789_123456789_123456789_1"); let description = String::from("123456789_123456789_"); let accounts = mpl_fixed_price_sale_accounts::CreateStore { admin: admin_wallet.pubkey(), store: store_keypair.pubkey(), system_program: system_program::id(), } .to_account_metas(None); let data = mpl_fixed_price_sale_instruction::CreateStore { name: name.to_owned(), description: description.to_owned(), } .data(); let instruction = Instruction { program_id: mpl_fixed_price_sale::id(), data, accounts, }; let tx = Transaction::new_signed_with_payer( &[instruction], Some(&context.payer.pubkey()), &[&context.payer, &admin_wallet, &store_keypair], context.last_blockhash, ); let tx_result = context.banks_client.process_transaction(tx).await; match tx_result.unwrap_err() { TransportError::Custom(_) => assert!(true), TransportError::TransactionError(_) => assert!(true), _ => assert!(false), } } #[tokio::test] async fn failure_description_is_long() { setup_context!(context, mpl_fixed_price_sale); let admin_wallet = Keypair::new(); let store_keypair = Keypair::new(); airdrop(&mut context, &admin_wallet.pubkey(), 10_000_000_000).await; let name = String::from("123456789_123456789_"); let description = String::from("123456789_123456789_123456789_123456789_123456789_123456789_1"); let accounts = mpl_fixed_price_sale_accounts::CreateStore { admin: admin_wallet.pubkey(), store: store_keypair.pubkey(), system_program: system_program::id(), } .to_account_metas(None); let data = mpl_fixed_price_sale_instruction::CreateStore { name: name.to_owned(), description: description.to_owned(), } .data(); let instruction = Instruction { program_id: mpl_fixed_price_sale::id(), data, accounts, }; let tx = Transaction::new_signed_with_payer( &[instruction], Some(&context.payer.pubkey()), &[&context.payer, &admin_wallet, &store_keypair], context.last_blockhash, ); let tx_result = context.banks_client.process_transaction(tx).await; match tx_result.unwrap_err() { TransportError::Custom(_) => assert!(true), TransportError::TransactionError(_) => assert!(true), _ => assert!(false), } } #[tokio::test] #[should_panic] async fn failure_signer_is_missed() { setup_context!(context, mpl_fixed_price_sale); let admin_wallet = Keypair::new(); let store_keypair = Keypair::new(); airdrop(&mut context, &admin_wallet.pubkey(), 10_000_000_000).await; let name = String::from("123456789_123456789_"); let description = String::from("123456789_123456789_"); let accounts = mpl_fixed_price_sale_accounts::CreateStore { admin: admin_wallet.pubkey(), store: store_keypair.pubkey(), system_program: system_program::id(), } .to_account_metas(None); let data = mpl_fixed_price_sale_instruction::CreateStore { name: name.to_owned(), description: description.to_owned(), } .data(); let instruction = Instruction { program_id: mpl_fixed_price_sale::id(), data, accounts, }; let tx = Transaction::new_signed_with_payer( &[instruction], Some(&context.payer.pubkey()), &[&context.payer, &admin_wallet], context.last_blockhash, ); context.banks_client.process_transaction(tx).await.unwrap(); } }
async fn success() { setup_context!(context, mpl_fixed_price_sale); let admin_wallet = Keypair::new(); let store_keypair = Keypair::new(); airdrop(&mut context, &admin_wallet.pubkey(), 10_000_000_000).await; let name = String::from("123456789_123456789_"); let description = String::from("123456789_123456789_123456789_"); let accounts = mpl_fixed_price_sale_accounts::CreateStore { admin: admin_wallet.pubkey(), store: store_keypair.pubkey(), system_program: system_program::id(), } .to_account_metas(None); let data = mpl_fixed_price_sale_instruction::CreateStore { name: name.to_owned(), description: description.to_owned(), } .data(); let instruction = Instruction { program_id: mpl_fixed_price_sale::id(), data, accounts, }; let tx = Transaction::new_signed_with_payer( &[instruction], Some(&context.payer.pubkey()), &[&context.payer, &admin_wallet, &store_keypair], context.last_blockhash, ); context.banks_client.process_transaction(tx).await.unwrap(); let store_acc = context .banks_client .get_account(store_keypair.pubkey()) .await .expect("account not found") .expect("account empty"); let store_data = Store::try_deserialize(&mut store_acc.data.as_ref()).unwrap(); assert_eq!(admin_wallet.pubkey(), store_data.admin); assert_eq!(puffed_out_string(name, NAME_MAX_LEN), store_data.name); assert_eq!( puffed_out_string(description, DESCRIPTION_MAX_LEN), store_data.description ); }
function_block-full_function
[ { "content": "/// Assert signer\n\npub fn assert_signer(account: &AccountInfo) -> ProgramResult {\n\n if account.is_signer {\n\n return Ok(());\n\n }\n\n\n\n Err(ProgramError::MissingRequiredSignature)\n\n}\n\n\n", "file_path": "nft-packs/program/src/utils.rs", "rank": 0, "score": 14...
Rust
src/providers/tpm_provider/key_management.rs
puiterwijk/parsec
47296bbbfd370e8137faf0e7df31586895c611a6
use super::utils; use super::utils::PasswordContext; use super::TpmProvider; use crate::authenticators::ApplicationName; use crate::key_info_managers; use crate::key_info_managers::KeyTriple; use crate::key_info_managers::{KeyInfo, ManageKeyInfo}; use log::error; use parsec_interface::operations::psa_key_attributes::*; use parsec_interface::operations::{ psa_destroy_key, psa_export_public_key, psa_generate_key, psa_import_key, }; use parsec_interface::requests::{ProviderID, ResponseStatus, Result}; use parsec_interface::secrecy::ExposeSecret; use picky_asn1_x509::RSAPublicKey; const PUBLIC_EXPONENT: [u8; 3] = [0x01, 0x00, 0x01]; const AUTH_VAL_LEN: usize = 32; fn insert_password_context( store_handle: &mut dyn ManageKeyInfo, key_triple: KeyTriple, password_context: PasswordContext, key_attributes: Attributes, ) -> Result<()> { let error_storing = |e| Err(key_info_managers::to_response_status(e)); let key_info = KeyInfo { id: bincode::serialize(&password_context)?, attributes: key_attributes, }; if store_handle .insert(key_triple, key_info) .or_else(error_storing)? .is_some() { error!("Inserting a mapping in the Key Info Manager that would overwrite an existing one."); Err(ResponseStatus::PsaErrorAlreadyExists) } else { Ok(()) } } pub fn get_password_context( store_handle: &dyn ManageKeyInfo, key_triple: KeyTriple, ) -> Result<(PasswordContext, Attributes)> { let key_info = store_handle .get(&key_triple) .map_err(key_info_managers::to_response_status)? .ok_or_else(|| { if crate::utils::GlobalConfig::log_error_details() { error!( "Key triple \"{}\" does not exist in the Key Info Manager.", key_triple ); } else { error!("Key triple does not exist in the Key Info Manager."); } ResponseStatus::PsaErrorDoesNotExist })?; Ok((bincode::deserialize(&key_info.id)?, key_info.attributes)) } impl TpmProvider { pub(super) fn psa_generate_key_internal( &self, app_name: ApplicationName, op: psa_generate_key::Operation, ) -> Result<psa_generate_key::Result> { let key_name = op.key_name; let attributes = op.attributes; let key_triple = KeyTriple::new(app_name, ProviderID::Tpm, key_name); let mut store_handle = self .key_info_store .write() .expect("Key store lock poisoned"); let mut esapi_context = self .esapi_context .lock() .expect("ESAPI Context lock poisoned"); let (key_context, auth_value) = esapi_context .create_signing_key(utils::parsec_to_tpm_params(attributes)?, AUTH_VAL_LEN) .map_err(|e| { format_error!("Error creating a RSA signing key", e); utils::to_response_status(e) })?; insert_password_context( &mut *store_handle, key_triple, PasswordContext { context: key_context, auth_value, }, attributes, )?; Ok(psa_generate_key::Result {}) } pub(super) fn psa_import_key_internal( &self, app_name: ApplicationName, op: psa_import_key::Operation, ) -> Result<psa_import_key::Result> { if op.attributes.key_type != Type::RsaPublicKey { error!("The TPM provider currently only supports importing RSA public key."); return Err(ResponseStatus::PsaErrorNotSupported); } let key_name = op.key_name; let attributes = op.attributes; let key_triple = KeyTriple::new(app_name, ProviderID::Tpm, key_name); let key_data = op.data; let mut store_handle = self .key_info_store .write() .expect("Key store lock poisoned"); let mut esapi_context = self .esapi_context .lock() .expect("ESAPI Context lock poisoned"); let public_key: RSAPublicKey = picky_asn1_der::from_bytes(key_data.expose_secret()) .map_err(|err| { format_error!("Could not deserialise key elements", err); ResponseStatus::PsaErrorInvalidArgument })?; if public_key.modulus.is_negative() || public_key.public_exponent.is_negative() { error!("Only positive modulus and public exponent are supported."); return Err(ResponseStatus::PsaErrorInvalidArgument); } if public_key.public_exponent.as_unsigned_bytes_be() != PUBLIC_EXPONENT { if crate::utils::GlobalConfig::log_error_details() { error!("The TPM Provider only supports 0x101 as public exponent for RSA public keys, {:?} given.", public_key.public_exponent.as_unsigned_bytes_be()); } else { error!( "The TPM Provider only supports 0x101 as public exponent for RSA public keys" ); } return Err(ResponseStatus::PsaErrorNotSupported); } let key_data = public_key.modulus.as_unsigned_bytes_be(); let len = key_data.len(); let key_bits = attributes.bits; if key_bits != 0 && len * 8 != key_bits { if crate::utils::GlobalConfig::log_error_details() { error!( "`bits` field of key attributes (value: {}) must be either 0 or equal to the size of the key in `data` (value: {}).", attributes.bits, len * 8 ); } else { error!("`bits` field of key attributes must be either 0 or equal to the size of the key in `data`."); } return Err(ResponseStatus::PsaErrorInvalidArgument); } if len != 128 && len != 256 { if crate::utils::GlobalConfig::log_error_details() { error!( "The TPM provider only supports 1024 and 2048 bits RSA public keys ({} bits given).", len * 8 ); } else { error!("The TPM provider only supports 1024 and 2048 bits RSA public keys"); } return Err(ResponseStatus::PsaErrorNotSupported); } let pub_key_context = esapi_context .load_external_rsa_public_key(&key_data) .map_err(|e| { format_error!("Error creating a RSA signing key", e); utils::to_response_status(e) })?; insert_password_context( &mut *store_handle, key_triple, PasswordContext { context: pub_key_context, auth_value: Vec::new(), }, attributes, )?; Ok(psa_import_key::Result {}) } pub(super) fn psa_export_public_key_internal( &self, app_name: ApplicationName, op: psa_export_public_key::Operation, ) -> Result<psa_export_public_key::Result> { let key_name = op.key_name; let key_triple = KeyTriple::new(app_name, ProviderID::Tpm, key_name); let store_handle = self.key_info_store.read().expect("Key store lock poisoned"); let mut esapi_context = self .esapi_context .lock() .expect("ESAPI Context lock poisoned"); let (password_context, key_attributes) = get_password_context(&*store_handle, key_triple)?; let pub_key_data = esapi_context .read_public_key(password_context.context) .map_err(|e| { format_error!("Error reading a public key", e); utils::to_response_status(e) })?; Ok(psa_export_public_key::Result { data: utils::pub_key_to_bytes(pub_key_data, key_attributes)?.into(), }) } pub(super) fn psa_destroy_key_internal( &self, app_name: ApplicationName, op: psa_destroy_key::Operation, ) -> Result<psa_destroy_key::Result> { let key_name = op.key_name; let key_triple = KeyTriple::new(app_name, ProviderID::Tpm, key_name); let mut store_handle = self .key_info_store .write() .expect("Key store lock poisoned"); if store_handle .remove(&key_triple) .map_err(key_info_managers::to_response_status)? .is_none() { if crate::utils::GlobalConfig::log_error_details() { error!( "Key triple \"{}\" does not exist in the Key Info Manager.", key_triple ); } else { error!("Key triple does not exist in the Key Info Manager."); } Err(ResponseStatus::PsaErrorDoesNotExist) } else { Ok(psa_destroy_key::Result {}) } } }
use super::utils; use super::utils::PasswordContext; use super::TpmProvider; use crate::authenticators::ApplicationName; use crate::key_info_managers; use crate::key_info_managers::KeyTriple; use crate::key_info_managers::{KeyInfo, ManageKeyInfo}; use log::error; use parsec_interface::operations::psa_key_attributes::*; use parsec_interface::operations::{ psa_destroy_key, psa_export_public_key, psa_generate_key, psa_import_key, }; use parsec_interface::requests::{ProviderID, ResponseStatus, Result}; use parsec_interface::secrecy::ExposeSecret; use picky_asn1_x509::RSAPublicKey; const PUBLIC_EXPONENT: [u8; 3] = [0x01, 0x00, 0x01]; const AUTH_VAL_LEN:
n psa_destroy_key_internal( &self, app_name: ApplicationName, op: psa_destroy_key::Operation, ) -> Result<psa_destroy_key::Result> { let key_name = op.key_name; let key_triple = KeyTriple::new(app_name, ProviderID::Tpm, key_name); let mut store_handle = self .key_info_store .write() .expect("Key store lock poisoned"); if store_handle .remove(&key_triple) .map_err(key_info_managers::to_response_status)? .is_none() { if crate::utils::GlobalConfig::log_error_details() { error!( "Key triple \"{}\" does not exist in the Key Info Manager.", key_triple ); } else { error!("Key triple does not exist in the Key Info Manager."); } Err(ResponseStatus::PsaErrorDoesNotExist) } else { Ok(psa_destroy_key::Result {}) } } }
usize = 32; fn insert_password_context( store_handle: &mut dyn ManageKeyInfo, key_triple: KeyTriple, password_context: PasswordContext, key_attributes: Attributes, ) -> Result<()> { let error_storing = |e| Err(key_info_managers::to_response_status(e)); let key_info = KeyInfo { id: bincode::serialize(&password_context)?, attributes: key_attributes, }; if store_handle .insert(key_triple, key_info) .or_else(error_storing)? .is_some() { error!("Inserting a mapping in the Key Info Manager that would overwrite an existing one."); Err(ResponseStatus::PsaErrorAlreadyExists) } else { Ok(()) } } pub fn get_password_context( store_handle: &dyn ManageKeyInfo, key_triple: KeyTriple, ) -> Result<(PasswordContext, Attributes)> { let key_info = store_handle .get(&key_triple) .map_err(key_info_managers::to_response_status)? .ok_or_else(|| { if crate::utils::GlobalConfig::log_error_details() { error!( "Key triple \"{}\" does not exist in the Key Info Manager.", key_triple ); } else { error!("Key triple does not exist in the Key Info Manager."); } ResponseStatus::PsaErrorDoesNotExist })?; Ok((bincode::deserialize(&key_info.id)?, key_info.attributes)) } impl TpmProvider { pub(super) fn psa_generate_key_internal( &self, app_name: ApplicationName, op: psa_generate_key::Operation, ) -> Result<psa_generate_key::Result> { let key_name = op.key_name; let attributes = op.attributes; let key_triple = KeyTriple::new(app_name, ProviderID::Tpm, key_name); let mut store_handle = self .key_info_store .write() .expect("Key store lock poisoned"); let mut esapi_context = self .esapi_context .lock() .expect("ESAPI Context lock poisoned"); let (key_context, auth_value) = esapi_context .create_signing_key(utils::parsec_to_tpm_params(attributes)?, AUTH_VAL_LEN) .map_err(|e| { format_error!("Error creating a RSA signing key", e); utils::to_response_status(e) })?; insert_password_context( &mut *store_handle, key_triple, PasswordContext { context: key_context, auth_value, }, attributes, )?; Ok(psa_generate_key::Result {}) } pub(super) fn psa_import_key_internal( &self, app_name: ApplicationName, op: psa_import_key::Operation, ) -> Result<psa_import_key::Result> { if op.attributes.key_type != Type::RsaPublicKey { error!("The TPM provider currently only supports importing RSA public key."); return Err(ResponseStatus::PsaErrorNotSupported); } let key_name = op.key_name; let attributes = op.attributes; let key_triple = KeyTriple::new(app_name, ProviderID::Tpm, key_name); let key_data = op.data; let mut store_handle = self .key_info_store .write() .expect("Key store lock poisoned"); let mut esapi_context = self .esapi_context .lock() .expect("ESAPI Context lock poisoned"); let public_key: RSAPublicKey = picky_asn1_der::from_bytes(key_data.expose_secret()) .map_err(|err| { format_error!("Could not deserialise key elements", err); ResponseStatus::PsaErrorInvalidArgument })?; if public_key.modulus.is_negative() || public_key.public_exponent.is_negative() { error!("Only positive modulus and public exponent are supported."); return Err(ResponseStatus::PsaErrorInvalidArgument); } if public_key.public_exponent.as_unsigned_bytes_be() != PUBLIC_EXPONENT { if crate::utils::GlobalConfig::log_error_details() { error!("The TPM Provider only supports 0x101 as public exponent for RSA public keys, {:?} given.", public_key.public_exponent.as_unsigned_bytes_be()); } else { error!( "The TPM Provider only supports 0x101 as public exponent for RSA public keys" ); } return Err(ResponseStatus::PsaErrorNotSupported); } let key_data = public_key.modulus.as_unsigned_bytes_be(); let len = key_data.len(); let key_bits = attributes.bits; if key_bits != 0 && len * 8 != key_bits { if crate::utils::GlobalConfig::log_error_details() { error!( "`bits` field of key attributes (value: {}) must be either 0 or equal to the size of the key in `data` (value: {}).", attributes.bits, len * 8 ); } else { error!("`bits` field of key attributes must be either 0 or equal to the size of the key in `data`."); } return Err(ResponseStatus::PsaErrorInvalidArgument); } if len != 128 && len != 256 { if crate::utils::GlobalConfig::log_error_details() { error!( "The TPM provider only supports 1024 and 2048 bits RSA public keys ({} bits given).", len * 8 ); } else { error!("The TPM provider only supports 1024 and 2048 bits RSA public keys"); } return Err(ResponseStatus::PsaErrorNotSupported); } let pub_key_context = esapi_context .load_external_rsa_public_key(&key_data) .map_err(|e| { format_error!("Error creating a RSA signing key", e); utils::to_response_status(e) })?; insert_password_context( &mut *store_handle, key_triple, PasswordContext { context: pub_key_context, auth_value: Vec::new(), }, attributes, )?; Ok(psa_import_key::Result {}) } pub(super) fn psa_export_public_key_internal( &self, app_name: ApplicationName, op: psa_export_public_key::Operation, ) -> Result<psa_export_public_key::Result> { let key_name = op.key_name; let key_triple = KeyTriple::new(app_name, ProviderID::Tpm, key_name); let store_handle = self.key_info_store.read().expect("Key store lock poisoned"); let mut esapi_context = self .esapi_context .lock() .expect("ESAPI Context lock poisoned"); let (password_context, key_attributes) = get_password_context(&*store_handle, key_triple)?; let pub_key_data = esapi_context .read_public_key(password_context.context) .map_err(|e| { format_error!("Error reading a public key", e); utils::to_response_status(e) })?; Ok(psa_export_public_key::Result { data: utils::pub_key_to_bytes(pub_key_data, key_attributes)?.into(), }) } pub(super) f
random
[ { "content": "/// Converts an OsStr reference to a byte array.\n\n///\n\n/// # Errors\n\n///\n\n/// Returns a custom std::io error if the conversion failed.\n\nfn os_str_to_u8_ref(os_str: &OsStr) -> std::io::Result<&[u8]> {\n\n match os_str.to_str() {\n\n Some(str) => Ok(str.as_bytes()),\n\n No...
Rust
src/parser/common.rs
rigetti/quil-rust
a4fb5a24233a55b32643b25dd014b0ec7af1c0c6
/** * Copyright 2021 Rigetti Computing * * 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 nom::{ branch::alt, combinator::{cut, map, opt, value}, multi::{many0, many1, separated_list0}, sequence::{delimited, preceded, tuple}, }; use crate::{ expected_token, expression::Expression, instruction::{ ArithmeticOperand, AttributeValue, FrameIdentifier, GateModifier, MemoryReference, Qubit, ScalarType, Vector, WaveformInvocation, }, parser::lexer::Operator, token, }; use super::{ error::{Error, ErrorKind}, expression::parse_expression, lexer::{DataType, Modifier, Token}, ParserInput, ParserResult, }; pub fn parse_arithmetic_operand<'a>(input: ParserInput<'a>) -> ParserResult<'a, ArithmeticOperand> { alt(( map( tuple((opt(token!(Operator(o))), token!(Float(v)))), |(op, v)| { let sign = match op { None => 1f64, Some(Operator::Minus) => -1f64, _ => panic!("Implement this error"), }; ArithmeticOperand::LiteralReal(sign * v) }, ), map( tuple((opt(token!(Operator(o))), token!(Integer(v)))), |(op, v)| { let sign = match op { None => 1, Some(Operator::Minus) => -1, _ => panic!("Implement this error"), }; ArithmeticOperand::LiteralInteger(sign * (v as i64)) }, ), map(parse_memory_reference, |f| { ArithmeticOperand::MemoryReference(f) }), ))(input) } pub fn parse_frame_attribute<'a>( input: ParserInput<'a>, ) -> ParserResult<'a, (String, AttributeValue)> { let (input, _) = token!(NewLine)(input)?; let (input, _) = token!(Indentation)(input)?; let (input, key) = token!(Identifier(v))(input)?; let (input, _) = token!(Colon)(input)?; let (input, value) = alt(( map(token!(String(v)), AttributeValue::String), map(parse_expression, |expression| { AttributeValue::Expression(expression) }), ))(input)?; Ok((input, (key, value))) } pub fn parse_frame_identifier<'a>(input: ParserInput<'a>) -> ParserResult<'a, FrameIdentifier> { let (input, qubits) = many1(parse_qubit)(input)?; let (input, name) = token!(String(v))(input)?; Ok((input, FrameIdentifier { name, qubits })) } pub fn parse_gate_modifier<'a>(input: ParserInput<'a>) -> ParserResult<'a, GateModifier> { let (input, token) = token!(Modifier(v))(input)?; Ok(( input, match token { Modifier::Controlled => GateModifier::Controlled, Modifier::Dagger => GateModifier::Dagger, Modifier::Forked => GateModifier::Forked, }, )) } pub fn parse_memory_reference<'a>(input: ParserInput<'a>) -> ParserResult<'a, MemoryReference> { let (input, name) = token!(Identifier(v))(input)?; let (input, index) = opt(delimited( token!(LBracket), token!(Integer(v)), token!(RBracket), ))(input)?; let index = index.unwrap_or(0); Ok((input, MemoryReference { name, index })) } pub fn parse_memory_reference_with_brackets<'a>( input: ParserInput<'a>, ) -> ParserResult<'a, MemoryReference> { let (input, name) = token!(Identifier(v))(input)?; let (input, index) = delimited(token!(LBracket), token!(Integer(v)), token!(RBracket))(input)?; Ok((input, MemoryReference { name, index })) } pub fn parse_named_argument<'a>(input: ParserInput<'a>) -> ParserResult<'a, (String, Expression)> { let (input, (name, _, value)) = tuple((token!(Identifier(v)), token!(Colon), parse_expression))(input)?; Ok((input, (name, value))) } pub fn parse_waveform_invocation<'a>( input: ParserInput<'a>, ) -> ParserResult<'a, WaveformInvocation> { let (input, name) = token!(Identifier(v))(input)?; let (input, parameter_tuples) = opt(delimited( token!(LParenthesis), cut(separated_list0(token!(Comma), parse_named_argument)), token!(RParenthesis), ))(input)?; let parameter_tuples = parameter_tuples.unwrap_or_default(); let parameters: HashMap<_, _> = parameter_tuples.into_iter().collect(); Ok((input, WaveformInvocation { name, parameters })) } pub fn parse_qubit(input: ParserInput) -> ParserResult<Qubit> { match input.split_first() { None => Err(nom::Err::Error(Error { input, error: ErrorKind::UnexpectedEOF("a qubit".to_owned()), })), Some((Token::Integer(value), remainder)) => Ok((remainder, Qubit::Fixed(*value))), Some((Token::Variable(name), remainder)) => Ok((remainder, Qubit::Variable(name.clone()))), Some((Token::Identifier(name), remainder)) => { Ok((remainder, Qubit::Variable(name.clone()))) } Some((other_token, _)) => { expected_token!(input, other_token, stringify!($expected_variant).to_owned()) } } } pub fn parse_variable_qubit(input: ParserInput) -> ParserResult<String> { match input.split_first() { None => Err(nom::Err::Error(Error { input, error: ErrorKind::UnexpectedEOF("a variable qubit".to_owned()), })), Some((Token::Variable(name), remainder)) => Ok((remainder, name.clone())), Some((Token::Identifier(name), remainder)) => Ok((remainder, name.clone())), Some((other_token, _)) => { expected_token!(input, other_token, stringify!($expected_variant).to_owned()) } } } pub fn parse_vector<'a>(input: ParserInput<'a>) -> ParserResult<'a, Vector> { let (input, data_type_token) = token!(DataType(v))(input)?; let data_type = match data_type_token { DataType::Bit => ScalarType::Bit, DataType::Integer => ScalarType::Integer, DataType::Real => ScalarType::Real, DataType::Octet => ScalarType::Octet, }; let (input, length) = opt(delimited( token!(LBracket), token!(Integer(v)), token!(RBracket), ))(input)?; let length = length.unwrap_or(1); Ok((input, Vector { data_type, length })) } pub fn skip_newlines_and_comments<'a>(input: ParserInput<'a>) -> ParserResult<'a, ()> { let (input, _) = many0(alt(( preceded(many0(token!(Indentation)), value((), token!(Comment(v)))), token!(NewLine), token!(Semicolon), )))(input)?; Ok((input, ())) } #[cfg(test)] mod describe_skip_newlines_and_comments { use crate::parser::lex; use super::skip_newlines_and_comments; #[test] fn it_skips_indented_comment() { let program = "\t # this is a comment X 0"; let tokens = lex(program); let (token_slice, _) = skip_newlines_and_comments(&tokens).unwrap(); let (_, expected) = tokens.split_at(3); assert_eq!(token_slice, expected); } #[test] fn it_skips_comments() { let program = "# this is a comment \n# and another\nX 0"; let tokens = lex(program); let (token_slice, _) = skip_newlines_and_comments(&tokens).unwrap(); let (_, expected) = tokens.split_at(4); assert_eq!(token_slice, expected); } #[test] fn it_skips_new_lines() { let program = "\nX 0"; let tokens = lex(program); let (token_slice, _) = skip_newlines_and_comments(&tokens).unwrap(); let (_, expected) = tokens.split_at(1); assert_eq!(token_slice, expected); } #[test] fn it_skips_semicolons() { let program = ";;;;;X 0"; let tokens = lex(program); let (token_slice, _) = skip_newlines_and_comments(&tokens).unwrap(); let (_, expected) = tokens.split_at(5); assert_eq!(token_slice, expected); } } #[cfg(test)] mod tests { use crate::{expression::Expression, instruction::MemoryReference, parser::lex, real}; use super::parse_waveform_invocation; #[test] fn waveform_invocation() { let input = "wf(a: 1.0, b: %var, c: ro[0])"; let lexed = lex(input); let (remainder, waveform) = parse_waveform_invocation(&lexed).unwrap(); assert_eq!(remainder, &[]); assert_eq!( waveform.parameters, vec![ ("a".to_owned(), Expression::Number(real!(1f64))), ("b".to_owned(), Expression::Variable("var".to_owned())), ( "c".to_owned(), Expression::Address(MemoryReference { name: "ro".to_owned(), index: 0 }) ) ] .into_iter() .collect() ) } }
/** * Copyright 2021 Rigetti Computing * * 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 nom::{ branch::alt, combinator::{cut, map, opt, value}, multi::{many0, many1, separated_list0}, sequence::{delimited, preceded, tuple}, }; use crate::{ expected_token, expression::Expression, instruction::{ ArithmeticOperand, AttributeValue, FrameIdentifier, GateModifier, MemoryReference, Qubit, ScalarType, Vector, WaveformInvocation, }, parser::lexer::Operator, token, }; use super::{ error::{Error, ErrorKind}, expression::parse_expression, lexer::{DataType, Modifier, Token}, ParserInput, ParserResult, }; pub fn parse_arithmetic_operand<'a>(input: ParserInput<'a>) -> ParserResult<'a, ArithmeticOperand> { alt(( map( tuple((opt(token!(Operator(o))), token!(Float(v)))), |(op, v)| { let sign = match op { None => 1f64, Some(Operator::Minus) => -1f64, _ => panic!("Implement this error"), }; ArithmeticOperand::LiteralReal(sign * v) }, ), map( tuple((opt(token!(Operator(o))), token!(Integer(v)))), |(op, v)| { let sign = match op { None => 1, Some(Operator::Minus) => -1, _ => panic!("Implement this error"), }; ArithmeticOperand::LiteralInteger(sign * (v as i64)) }, ), map(parse_memory_reference, |f| { ArithmeticOperand::MemoryReference(f) }), ))(input) } pub fn parse_frame_attribute<'a>( input: ParserInput<'a>, ) -> ParserResult<'a, (String, AttributeValue)> { let (input, _) = token!(NewLine)(input)?; let (input, _) = token!(Indentation)(input)?; let (input, key) = token!(Identifier(v))(input)?; let (input, _) = token!(Colon)(input)?; let (input, value) = alt(( map(token!(String(v)), AttributeValue::String), map(parse_expression, |expression| { AttributeValue::Expression(expression) }), ))(input)?; Ok((input, (key, value))) } pub fn parse_frame_identifier<'a>(input: ParserInput<'a>) -> ParserResult<'a, FrameIdentifier> { let (input, qubits) = many1(parse_qubit)(input)?; let (input, name) = token!(String(v))(input)?; Ok((input, FrameIdentifier { name, qubits })) } pub fn parse_gate_modifier<'a>(input: ParserInput<'a>) -> ParserResult<'a, GateModifier> { let (input, token) = token!(Modifier(v))(input)?; Ok(( input, match token { Modifier::Controlled => GateModifier::Controlled, Modifier::Dagger => GateModifier::Dagger, Modifier::Forked => GateModifier::Forked, }, )) } pub fn parse_memory_reference<'a>(input: ParserInput<'a>) -> ParserResult<'a, MemoryReference> { let (input, name) = token!(Identifier(v))(input)?; let (input, index) = opt(delimited( token!(LBracket), token!(Integer(v)), token!(RBracket), ))(input)?; let index = index.unwrap_or(0); Ok((input, MemoryReference { name, index })) } pub fn parse_memory_reference_with_brackets<'a>( input: ParserInput<'a>, ) -> ParserResult<'a, MemoryReference> { let (input, name) = token!(Identifier(v))(input)?; let (input, index) = delimited(token!(LBracket), token!(Integer(v)), token!(RBracket))(input)?; Ok((input, MemoryReference { name, index })) } pub fn parse_named_argument<'a>(input: ParserInput<'a>) -> ParserResult<'a, (String, Expression)> { let (input, (name, _, value)) = tuple((token!(Identifier(v)), token!(Colon), parse_expression))(input)?; Ok((input, (name, value))) } pub fn parse_waveform_invocation<'a>( input: ParserInput<'a>, ) -> ParserResult<'a, WaveformInvocation> { let (input, name) = token!(Identifier(v))(input)?; let (input, parameter_tuples) = opt(delimited( token!(LParenthesis), cut(separated_list0(token!(Comma), parse_named_argument)), token!(RParenthesis), ))(input)?; let parameter_tuples = parameter_tuples.unwrap_or_default(); let parameters: HashMap<_, _> = parameter_tuples.into_iter().collect(); Ok((input, WaveformInvocation { name, parameters })) } pub fn parse_qubit(input: ParserInput) -> ParserResult<Qubit> { match input.split_first() { None => Err(nom::Err::Error(Error { input, error: ErrorKind::UnexpectedEOF("a qubit".to_owned()), })), Some((Token::Integer(value), remainder)) => Ok((remainder, Qubit::Fixed(*value))), Some((Token::Variable(name), remainder)) => Ok((remainder, Qubit::Variable(name.clone()))), Some((Token::Identifier(name), remainder)) => { Ok((remainder, Qubit::Variable(name.clone()))) } Some((other_token, _)) => { expected_token!(input, other_token, stringify!($expected_variant).to_owned()) } } } pub fn parse_variable_qubit(input: ParserInput) -> ParserResult<String> { match input.split_first() { None =>
, Some((Token::Variable(name), remainder)) => Ok((remainder, name.clone())), Some((Token::Identifier(name), remainder)) => Ok((remainder, name.clone())), Some((other_token, _)) => { expected_token!(input, other_token, stringify!($expected_variant).to_owned()) } } } pub fn parse_vector<'a>(input: ParserInput<'a>) -> ParserResult<'a, Vector> { let (input, data_type_token) = token!(DataType(v))(input)?; let data_type = match data_type_token { DataType::Bit => ScalarType::Bit, DataType::Integer => ScalarType::Integer, DataType::Real => ScalarType::Real, DataType::Octet => ScalarType::Octet, }; let (input, length) = opt(delimited( token!(LBracket), token!(Integer(v)), token!(RBracket), ))(input)?; let length = length.unwrap_or(1); Ok((input, Vector { data_type, length })) } pub fn skip_newlines_and_comments<'a>(input: ParserInput<'a>) -> ParserResult<'a, ()> { let (input, _) = many0(alt(( preceded(many0(token!(Indentation)), value((), token!(Comment(v)))), token!(NewLine), token!(Semicolon), )))(input)?; Ok((input, ())) } #[cfg(test)] mod describe_skip_newlines_and_comments { use crate::parser::lex; use super::skip_newlines_and_comments; #[test] fn it_skips_indented_comment() { let program = "\t # this is a comment X 0"; let tokens = lex(program); let (token_slice, _) = skip_newlines_and_comments(&tokens).unwrap(); let (_, expected) = tokens.split_at(3); assert_eq!(token_slice, expected); } #[test] fn it_skips_comments() { let program = "# this is a comment \n# and another\nX 0"; let tokens = lex(program); let (token_slice, _) = skip_newlines_and_comments(&tokens).unwrap(); let (_, expected) = tokens.split_at(4); assert_eq!(token_slice, expected); } #[test] fn it_skips_new_lines() { let program = "\nX 0"; let tokens = lex(program); let (token_slice, _) = skip_newlines_and_comments(&tokens).unwrap(); let (_, expected) = tokens.split_at(1); assert_eq!(token_slice, expected); } #[test] fn it_skips_semicolons() { let program = ";;;;;X 0"; let tokens = lex(program); let (token_slice, _) = skip_newlines_and_comments(&tokens).unwrap(); let (_, expected) = tokens.split_at(5); assert_eq!(token_slice, expected); } } #[cfg(test)] mod tests { use crate::{expression::Expression, instruction::MemoryReference, parser::lex, real}; use super::parse_waveform_invocation; #[test] fn waveform_invocation() { let input = "wf(a: 1.0, b: %var, c: ro[0])"; let lexed = lex(input); let (remainder, waveform) = parse_waveform_invocation(&lexed).unwrap(); assert_eq!(remainder, &[]); assert_eq!( waveform.parameters, vec![ ("a".to_owned(), Expression::Number(real!(1f64))), ("b".to_owned(), Expression::Variable("var".to_owned())), ( "c".to_owned(), Expression::Address(MemoryReference { name: "ro".to_owned(), index: 0 }) ) ] .into_iter() .collect() ) } }
Err(nom::Err::Error(Error { input, error: ErrorKind::UnexpectedEOF("a variable qubit".to_owned()), }))
call_expression
[ { "content": "pub fn get_expression_parameter_string(parameters: &[Expression]) -> String {\n\n if parameters.is_empty() {\n\n return String::from(\"\");\n\n }\n\n\n\n let parameter_str: String = parameters.iter().map(|e| format!(\"{}\", e)).collect();\n\n format!(\"({})\", parameter_str)\n\n...
Rust
src/factor/bfs.rs
y011d4/factor-from-random-known-bits
ee9ade6f5a21618e701ffacba320670abd069434
use crate::util::{bits_to_num, TWO}; use rug::{ops::Pow, Integer}; use std::collections::VecDeque; fn check(p: &Integer, q: &Integer, n: &Integer, m: u32) -> bool { let two_pow = TWO.clone().pow(m); let mut tmp_n = p.clone(); tmp_n *= q; tmp_n %= &two_pow; let mut n_two_pow = n.clone(); n_two_pow %= &two_pow; return tmp_n == n_two_pow; } pub fn factor_bfs( n: &Integer, p_bits: Vec<i8>, q_bits: Vec<i8>, bit_len: usize, verbose: bool, ) -> Option<(Integer, Integer)> { let mut ans: Option<(Integer, Integer)> = None; let mut queue: VecDeque<((Vec<i8>, Integer), (Vec<i8>, Integer), i32)> = VecDeque::new(); queue.push_back(( (p_bits, "0".parse().unwrap()), (q_bits, "0".parse().unwrap()), -1, )); let mut fixed_idx: i32; while queue.len() != 0 { let tmp = queue.pop_front().unwrap(); let (p_bits, saved_p) = tmp.0; let (q_bits, saved_q) = tmp.1; let saved_idx = tmp.2; let mut idx = 0.max(saved_idx); while idx < bit_len as i32 { if p_bits[idx as usize] == -1 || q_bits[idx as usize] == -1 { break; } idx += 1; } fixed_idx = idx - 1; if verbose { print!( "\rSearched index: {:<8?} Queue size: {:<8?}", fixed_idx, queue.len() ); } let tmp_p: Integer = bits_to_num(&p_bits, fixed_idx + 1, &saved_p, saved_idx); let tmp_q: Integer = bits_to_num(&q_bits, fixed_idx + 1, &saved_q, saved_idx); let two_pow = TWO.clone().pow((fixed_idx + 1) as u32); let mut tmp_n = tmp_p.clone(); tmp_n *= &tmp_q; if &tmp_n == n { ans = Some((tmp_p, tmp_q)); break; } tmp_n %= &two_pow; let mut n_two_pow = n.clone(); n_two_pow %= &two_pow; if tmp_n != n_two_pow { continue; } if fixed_idx + 1 == bit_len as i32 { continue; } let tmp_p_two_pow = match p_bits[idx as usize] { -1 => { let mut ret = tmp_p.clone(); ret += &two_pow; ret } _ => "0".parse().unwrap(), }; let tmp_q_two_pow = match q_bits[idx as usize] { -1 => { let mut ret = tmp_q.clone(); ret += &two_pow; ret } _ => "0".parse().unwrap(), }; if (p_bits[idx as usize] == -1) && (q_bits[idx as usize] == -1) { if check(&tmp_p, &tmp_q, &n, (fixed_idx + 2) as u32) { let mut tmp_p_bits_0 = p_bits.clone(); tmp_p_bits_0[idx as usize] = 0; let mut tmp_q_bits_0 = q_bits.clone(); tmp_q_bits_0[idx as usize] = 0; queue.push_back(( (tmp_p_bits_0, tmp_p.clone()), (tmp_q_bits_0, tmp_q.clone()), fixed_idx + 1, )); } if check(&tmp_p, &tmp_q_two_pow, &n, (fixed_idx + 2) as u32) { let mut tmp_p_bits_0 = p_bits.clone(); tmp_p_bits_0[idx as usize] = 0; let mut tmp_q_bits_1 = q_bits.clone(); tmp_q_bits_1[idx as usize] = 1; queue.push_back(( (tmp_p_bits_0, tmp_p.clone()), (tmp_q_bits_1, tmp_q_two_pow.clone()), fixed_idx + 1, )); } if check(&tmp_p_two_pow, &tmp_q, &n, (fixed_idx + 2) as u32) { let mut tmp_p_bits_1 = p_bits.clone(); tmp_p_bits_1[idx as usize] = 1; let mut tmp_q_bits_0 = q_bits.clone(); tmp_q_bits_0[idx as usize] = 0; queue.push_back(( (tmp_p_bits_1, tmp_p_two_pow.clone()), (tmp_q_bits_0, tmp_q.clone()), fixed_idx + 1, )); } if check(&tmp_p_two_pow, &tmp_q_two_pow, &n, (fixed_idx + 2) as u32) { let mut tmp_p_bits_1 = p_bits.clone(); tmp_p_bits_1[idx as usize] = 1; let mut tmp_q_bits_1 = q_bits.clone(); tmp_q_bits_1[idx as usize] = 1; queue.push_back(( (tmp_p_bits_1, tmp_p_two_pow), (tmp_q_bits_1, tmp_q_two_pow), fixed_idx + 1, )); } } else if p_bits[idx as usize] == -1 { let tmp_q_next = match q_bits[(fixed_idx + 1) as usize] { 0 => tmp_q.clone(), 1 => { let mut ret = tmp_q.clone(); ret += two_pow; ret } _ => panic!(), }; if check(&tmp_p, &tmp_q_next, &n, (fixed_idx + 2) as u32) { let mut tmp_p_bits_0 = p_bits.clone(); tmp_p_bits_0[idx as usize] = 0; queue.push_back(( (tmp_p_bits_0, tmp_p.clone()), (q_bits.clone(), tmp_q_next.clone()), fixed_idx + 1, )); } if check(&tmp_p_two_pow, &tmp_q_next, &n, (fixed_idx + 2) as u32) { let mut tmp_p_bits_1 = p_bits.clone(); tmp_p_bits_1[idx as usize] = 1; queue.push_back(( (tmp_p_bits_1, tmp_p_two_pow.clone()), (q_bits.clone(), tmp_q_next.clone()), fixed_idx + 1, )); } } else if q_bits[idx as usize] == -1 { let tmp_p_next = match p_bits[(fixed_idx + 1) as usize] { 0 => tmp_p.clone(), 1 => { let mut ret = tmp_p.clone(); ret += two_pow; ret } _ => panic!(), }; if check(&tmp_p_next, &tmp_q, &n, (fixed_idx + 2) as u32) { let mut tmp_q_bits_0 = q_bits.clone(); tmp_q_bits_0[idx as usize] = 0; queue.push_back(( (p_bits.clone(), tmp_p_next.clone()), (tmp_q_bits_0, tmp_q.clone()), fixed_idx + 1, )); } if check(&tmp_p_next, &tmp_q_two_pow, &n, (fixed_idx + 2) as u32) { let mut tmp_q_bits_1 = q_bits.clone(); tmp_q_bits_1[idx as usize] = 1; queue.push_back(( (p_bits.clone(), tmp_p_next.clone()), (tmp_q_bits_1, tmp_q_two_pow.clone()), fixed_idx + 1, )); } } else { panic!("そうはならんやろ"); } } if verbose { println!(); } ans } #[cfg(test)] mod tests { use super::*; #[test] fn test_factor() { let n: Integer = "323".parse().unwrap(); let p_bits = vec![-1, -1, -1, -1, -1]; let q_bits = vec![-1, 1, -1, -1, -1]; let bit_len = 5; let expected: Option<(Integer, Integer)> = Some(("17".parse().unwrap(), "19".parse().unwrap())); assert_eq!( factor_bfs(&n, p_bits.clone(), q_bits.clone(), bit_len, false), expected ); } }
use crate::util::{bits_to_num, TWO}; use rug::{ops::Pow, Integer}; use std::collections::VecDeque; fn check(p: &Integer, q: &Integer, n: &Integer, m: u32) -> bool { let two_pow = TWO.clone().pow(m); let mut tmp_n = p.clone(); tmp_n *= q; tmp_n %= &two_pow; let mut n_two_pow = n.clone(); n_two_pow %= &two_pow; return tmp_n == n_two_pow; } pub fn factor_bfs( n: &Integer, p_bits: Vec<i8>, q_bits: Vec<i8>, bit_len: usize, verbose: bool, ) -> Option<(Integer, Integer)> { let mut ans: Option<(Integer, Integer)> = None; let mut queue: VecDeque<((Vec<i8>, Integer), (Vec<i8>, Integer), i32)> = VecDeque::new(); queue.push_back(( (p_bits, "0".parse().unwrap()), (q_bits, "0".parse().unwrap()), -1, )); let mut fixed_idx: i32; while queue.len() != 0 { let tmp = queue.pop_front().unwrap(); let (p_bits, saved_p) = tmp.0; let (q_bits, saved_q) = tmp.1; let saved_idx = tmp.2; let mut idx = 0.max(saved_idx); while idx < bit_len as i32 { if p_bits[idx as usize] == -1 || q_bits[idx as usize] == -1 { break; } idx += 1; } fixed_idx = idx - 1; if verbose { print!( "\rSearched index: {:<8?} Queue size: {:<8?}", fixed_idx, queue.len() ); } let tmp_p: Integer = bits_to_num(&p_bits, fixed_idx + 1, &saved_p, saved_idx); let tmp_q: Integer = bits_to_num(&q_bits, fixed_idx + 1, &saved_q, saved_idx); let two_pow = TWO.clone().pow((fixed_idx + 1) as u32); let mut tmp_n = tmp_p.clone(); tmp_n *= &tmp_q; if &tmp_n == n { ans = Some((tmp_p, tmp_q)); break; } tmp_n %= &two_pow; let mut n_two_pow = n.clone(); n_two_pow %= &two_pow; if tmp_n != n_two_pow { continue; } if fixed_idx + 1 == bit_len as i32 { continue; } let tmp_p_two_pow = match p_bits[idx as usize] { -1 => { let mut ret = tmp_p.clone(); ret += &two_pow; ret } _ => "0".parse().unwrap(), }; let tmp_q_two_pow = match q_bits[idx as usize] { -1 => { let mut ret = tmp_q.clone(); ret += &two_pow; ret } _ => "0".parse().unwrap(), }; if (p_bits[idx as usize] == -1) && (q_bits[idx as usize] == -1) { if check(&tmp_p, &tmp_q, &n, (fixed_idx + 2) as u32) { let mut tmp_p_bits_0 = p_bits.clone(); tmp_p_bits_0[idx as usize] = 0; let mut tmp_q_bits_0 = q_bits.clone(); tmp_q_bits_0[idx as usize] = 0; queue.push_back(( (tmp_p_bits_0, tmp_p.clone()), (tmp_q_bits_0, tmp_q.clone()), fixed_idx + 1, )); } if check(&tmp_p, &tmp_q_two_pow, &n, (fixed_idx + 2) as u32) { let mut tmp_p_bits_0 = p_bits.clone(); tmp_p_bits_0[idx as usize] = 0; let mut tmp_q_bits_1 = q_bits.clone(); tmp_q_bits_1[idx as usize] = 1; queue.push_back(( (tmp_p_bits_0, tmp_p.clone()), (tmp_q_bits_1, tmp_q_two_pow.clone()), fixed_idx + 1, )); } if check(&tmp_p_two_pow, &tmp_q, &n, (fixed_idx + 2) as u32) { let mut tmp_p_bits_1 = p_bits.clone(); tmp_p_bits_1[idx as usize] = 1; let mut tmp_q_bits_0 = q_bits.clone(); tmp_q_bits_0[idx as usize] = 0; queue.push_back(( (tmp_p_bits_1, tmp_p_two_pow.clone()), (tmp_q_bits_0, tmp_q.clone()), fixed_idx + 1, )); } if check(&tmp_p_two_pow, &tmp_q_two_pow, &n, (fixed_idx + 2) as u32) { let mut tmp_p_bits_1 = p_bits.clone(); tmp_p_bits_1[idx as usize] = 1; let mut tmp_q_bits_1 = q_bits.clone(); tmp_q_bits_1[idx as usize] = 1; queue.push_back(( (tmp_p_bits_1, tmp_p_two_pow), (tmp_q_bits_1, tmp_q_two_pow), fixed_idx + 1, )); } } else if p_bits[idx as usize] == -1 { let tmp_q_next = match q_bits[(fixed_idx + 1) as usize] { 0 => tmp_q.clone(), 1 => { let mut ret = tmp_q.clone(); ret += two_pow; ret } _ => panic!(), }; if check(&tmp_p, &tmp_q_next, &n, (fixed_idx + 2) as u32) { let mut tmp_p_bits_0 = p_bits.clone(); tmp_p_bits_0[idx as usize] = 0; queue.push_back(( (tmp_p_bits_0, tmp_p.clone()), (q_bits.clone(), tmp_q_next.clone()), fixed_idx + 1, )); } if check(&tmp_p_two_pow, &tmp_q_next, &n, (fixed_idx + 2) as u32) { let mut tmp_p_bits_1 = p_bits.clone(); tmp_p_bits_1[idx as usize] = 1; queue.push_back(( (tmp_p_bits_1, tmp_p_two_pow.clone()), (q_bits.clone(), tmp_q_next.clone()), fixed_idx + 1, )); } } else if q_bits[idx as usize] == -1 { let tmp_p_next =
; if check(&tmp_p_next, &tmp_q, &n, (fixed_idx + 2) as u32) { let mut tmp_q_bits_0 = q_bits.clone(); tmp_q_bits_0[idx as usize] = 0; queue.push_back(( (p_bits.clone(), tmp_p_next.clone()), (tmp_q_bits_0, tmp_q.clone()), fixed_idx + 1, )); } if check(&tmp_p_next, &tmp_q_two_pow, &n, (fixed_idx + 2) as u32) { let mut tmp_q_bits_1 = q_bits.clone(); tmp_q_bits_1[idx as usize] = 1; queue.push_back(( (p_bits.clone(), tmp_p_next.clone()), (tmp_q_bits_1, tmp_q_two_pow.clone()), fixed_idx + 1, )); } } else { panic!("そうはならんやろ"); } } if verbose { println!(); } ans } #[cfg(test)] mod tests { use super::*; #[test] fn test_factor() { let n: Integer = "323".parse().unwrap(); let p_bits = vec![-1, -1, -1, -1, -1]; let q_bits = vec![-1, 1, -1, -1, -1]; let bit_len = 5; let expected: Option<(Integer, Integer)> = Some(("17".parse().unwrap(), "19".parse().unwrap())); assert_eq!( factor_bfs(&n, p_bits.clone(), q_bits.clone(), bit_len, false), expected ); } }
match p_bits[(fixed_idx + 1) as usize] { 0 => tmp_p.clone(), 1 => { let mut ret = tmp_p.clone(); ret += two_pow; ret } _ => panic!(), }
if_condition
[ { "content": "pub fn bits_to_num(bits: &Vec<i8>, n: i32, saved: &Integer, saved_idx: i32) -> Integer {\n\n let mut ret = saved.clone();\n\n for i in (saved_idx as usize + 1)..(n as usize) {\n\n assert_ne!(bits[i], -1);\n\n if bits[i] == 1 {\n\n ret += TWO.clone().pow(i as u32) * b...
Rust
core/src/avm1/globals/text_field.rs
hthh/ruffle
b4624fddce5a4b581244a4388adef2a9ea41bb92
use crate::avm1::function::Executable; use crate::avm1::property::Attribute::*; use crate::avm1::return_value::ReturnValue; use crate::avm1::{Avm1, Error, Object, ScriptObject, TObject, UpdateContext, Value}; use crate::display_object::{EditText, TDisplayObject}; use crate::font::TextFormat; use gc_arena::MutationContext; pub fn constructor<'gc>( _avm: &mut Avm1<'gc>, _context: &mut UpdateContext<'_, 'gc, '_>, _this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { Ok(Value::Undefined.into()) } pub fn get_text<'gc>( _avm: &mut Avm1<'gc>, _context: &mut UpdateContext<'_, 'gc, '_>, this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { if let Some(display_object) = this.as_display_object() { if let Some(text_field) = display_object.as_edit_text() { return Ok(text_field.text().into()); } } Ok(Value::Undefined.into()) } pub fn set_text<'gc>( avm: &mut Avm1<'gc>, context: &mut UpdateContext<'_, 'gc, '_>, this: Object<'gc>, args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { if let Some(display_object) = this.as_display_object() { if let Some(text_field) = display_object.as_edit_text() { if let Some(value) = args.get(0) { text_field.set_text( value .to_owned() .coerce_to_string(avm, context) .unwrap_or_else(|_| "undefined".to_string()), context.gc_context, ) } } } Ok(Value::Undefined.into()) } macro_rules! with_text_field { ( $gc_context: ident, $object:ident, $fn_proto: expr, $($name:expr => $fn:expr),* ) => {{ $( $object.force_set_function( $name, |avm, context: &mut UpdateContext<'_, 'gc, '_>, this, args| -> Result<ReturnValue<'gc>, Error> { if let Some(display_object) = this.as_display_object() { if let Some(text_field) = display_object.as_edit_text() { return $fn(text_field, avm, context, args); } } Ok(Value::Undefined.into()) } as crate::avm1::function::NativeFunction<'gc>, $gc_context, DontDelete | ReadOnly | DontEnum, $fn_proto ); )* }}; } pub fn text_width<'gc>( _avm: &mut Avm1<'gc>, context: &mut UpdateContext<'_, 'gc, '_>, this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { if let Some(etext) = this .as_display_object() .and_then(|dobj| dobj.as_edit_text()) { let metrics = etext.measure_text(context); return Ok(metrics.0.to_pixels().into()); } Ok(Value::Undefined.into()) } pub fn text_height<'gc>( _avm: &mut Avm1<'gc>, context: &mut UpdateContext<'_, 'gc, '_>, this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { if let Some(etext) = this .as_display_object() .and_then(|dobj| dobj.as_edit_text()) { let metrics = etext.measure_text(context); return Ok(metrics.1.to_pixels().into()); } Ok(Value::Undefined.into()) } pub fn multiline<'gc>( _avm: &mut Avm1<'gc>, _context: &mut UpdateContext<'_, 'gc, '_>, this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { if let Some(etext) = this .as_display_object() .and_then(|dobj| dobj.as_edit_text()) { return Ok(etext.is_multiline().into()); } Ok(Value::Undefined.into()) } pub fn set_multiline<'gc>( avm: &mut Avm1<'gc>, context: &mut UpdateContext<'_, 'gc, '_>, this: Object<'gc>, args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { let is_multiline = args .get(0) .cloned() .unwrap_or(Value::Undefined) .as_bool(avm.current_swf_version()); if let Some(etext) = this .as_display_object() .and_then(|dobj| dobj.as_edit_text()) { etext.set_multiline(is_multiline, context.gc_context); } Ok(Value::Undefined.into()) } pub fn word_wrap<'gc>( _avm: &mut Avm1<'gc>, _context: &mut UpdateContext<'_, 'gc, '_>, this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { if let Some(etext) = this .as_display_object() .and_then(|dobj| dobj.as_edit_text()) { return Ok(etext.is_word_wrap().into()); } Ok(Value::Undefined.into()) } pub fn set_word_wrap<'gc>( avm: &mut Avm1<'gc>, context: &mut UpdateContext<'_, 'gc, '_>, this: Object<'gc>, args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { let is_word_wrap = args .get(0) .cloned() .unwrap_or(Value::Undefined) .as_bool(avm.current_swf_version()); if let Some(etext) = this .as_display_object() .and_then(|dobj| dobj.as_edit_text()) { etext.set_word_wrap(is_word_wrap, context.gc_context); } Ok(Value::Undefined.into()) } pub fn create_proto<'gc>( gc_context: MutationContext<'gc, '_>, proto: Object<'gc>, fn_proto: Object<'gc>, ) -> Object<'gc> { let mut object = ScriptObject::object(gc_context, Some(proto)); with_text_field!( gc_context, object, Some(fn_proto), "toString" => |text_field: EditText<'gc>, _avm: &mut Avm1<'gc>, _context: &mut UpdateContext<'_, 'gc, '_>, _args| { Ok(text_field.path().into()) }, "getNewTextFormat" => |text_field: EditText<'gc>, avm: &mut Avm1<'gc>, context: &mut UpdateContext<'_, 'gc, '_>, _args| { let tf = text_field.new_text_format(); Ok(tf.as_avm1_object(avm, context)?.into()) }, "setNewTextFormat" => |text_field: EditText<'gc>, avm: &mut Avm1<'gc>, context: &mut UpdateContext<'_, 'gc, '_>, args: &[Value<'gc>]| { let tf = args.get(0).cloned().unwrap_or(Value::Undefined); if let Value::Object(tf) = tf { let tf_parsed = TextFormat::from_avm1_object(tf, avm, context)?; text_field.set_new_text_format(tf_parsed, context.gc_context); } Ok(Value::Undefined.into()) } ); object.into() } pub fn attach_virtual_properties<'gc>(gc_context: MutationContext<'gc, '_>, object: Object<'gc>) { object.add_property( gc_context, "text", Executable::Native(get_text), Some(Executable::Native(set_text)), DontDelete | ReadOnly | DontEnum, ); object.add_property( gc_context, "textWidth", Executable::Native(text_width), None, ReadOnly.into(), ); object.add_property( gc_context, "textHeight", Executable::Native(text_height), None, ReadOnly.into(), ); object.add_property( gc_context, "multiline", Executable::Native(multiline), Some(Executable::Native(set_multiline)), ReadOnly.into(), ); object.add_property( gc_context, "wordWrap", Executable::Native(word_wrap), Some(Executable::Native(set_word_wrap)), ReadOnly.into(), ); }
use crate::avm1::function::Executable; use crate::avm1::property::Attribute::*; use crate::avm1::return_value::ReturnValue; use crate::avm1::{Avm1, Error, Object, ScriptObject, TObject, UpdateContext, Value}; use crate::display_object::{EditText, TDisplayObject}; use crate::font::TextFormat; use gc_arena::MutationContext;
pub fn get_text<'gc>( _avm: &mut Avm1<'gc>, _context: &mut UpdateContext<'_, 'gc, '_>, this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { if let Some(display_object) = this.as_display_object() { if let Some(text_field) = display_object.as_edit_text() { return Ok(text_field.text().into()); } } Ok(Value::Undefined.into()) } pub fn set_text<'gc>( avm: &mut Avm1<'gc>, context: &mut UpdateContext<'_, 'gc, '_>, this: Object<'gc>, args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { if let Some(display_object) = this.as_display_object() { if let Some(text_field) = display_object.as_edit_text() { if let Some(value) = args.get(0) { text_field.set_text( value .to_owned() .coerce_to_string(avm, context) .unwrap_or_else(|_| "undefined".to_string()), context.gc_context, ) } } } Ok(Value::Undefined.into()) } macro_rules! with_text_field { ( $gc_context: ident, $object:ident, $fn_proto: expr, $($name:expr => $fn:expr),* ) => {{ $( $object.force_set_function( $name, |avm, context: &mut UpdateContext<'_, 'gc, '_>, this, args| -> Result<ReturnValue<'gc>, Error> { if let Some(display_object) = this.as_display_object() { if let Some(text_field) = display_object.as_edit_text() { return $fn(text_field, avm, context, args); } } Ok(Value::Undefined.into()) } as crate::avm1::function::NativeFunction<'gc>, $gc_context, DontDelete | ReadOnly | DontEnum, $fn_proto ); )* }}; } pub fn text_width<'gc>( _avm: &mut Avm1<'gc>, context: &mut UpdateContext<'_, 'gc, '_>, this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { if let Some(etext) = this .as_display_object() .and_then(|dobj| dobj.as_edit_text()) { let metrics = etext.measure_text(context); return Ok(metrics.0.to_pixels().into()); } Ok(Value::Undefined.into()) } pub fn text_height<'gc>( _avm: &mut Avm1<'gc>, context: &mut UpdateContext<'_, 'gc, '_>, this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { if let Some(etext) = this .as_display_object() .and_then(|dobj| dobj.as_edit_text()) { let metrics = etext.measure_text(context); return Ok(metrics.1.to_pixels().into()); } Ok(Value::Undefined.into()) } pub fn multiline<'gc>( _avm: &mut Avm1<'gc>, _context: &mut UpdateContext<'_, 'gc, '_>, this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { if let Some(etext) = this .as_display_object() .and_then(|dobj| dobj.as_edit_text()) { return Ok(etext.is_multiline().into()); } Ok(Value::Undefined.into()) } pub fn set_multiline<'gc>( avm: &mut Avm1<'gc>, context: &mut UpdateContext<'_, 'gc, '_>, this: Object<'gc>, args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { let is_multiline = args .get(0) .cloned() .unwrap_or(Value::Undefined) .as_bool(avm.current_swf_version()); if let Some(etext) = this .as_display_object() .and_then(|dobj| dobj.as_edit_text()) { etext.set_multiline(is_multiline, context.gc_context); } Ok(Value::Undefined.into()) } pub fn word_wrap<'gc>( _avm: &mut Avm1<'gc>, _context: &mut UpdateContext<'_, 'gc, '_>, this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { if let Some(etext) = this .as_display_object() .and_then(|dobj| dobj.as_edit_text()) { return Ok(etext.is_word_wrap().into()); } Ok(Value::Undefined.into()) } pub fn set_word_wrap<'gc>( avm: &mut Avm1<'gc>, context: &mut UpdateContext<'_, 'gc, '_>, this: Object<'gc>, args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { let is_word_wrap = args .get(0) .cloned() .unwrap_or(Value::Undefined) .as_bool(avm.current_swf_version()); if let Some(etext) = this .as_display_object() .and_then(|dobj| dobj.as_edit_text()) { etext.set_word_wrap(is_word_wrap, context.gc_context); } Ok(Value::Undefined.into()) } pub fn create_proto<'gc>( gc_context: MutationContext<'gc, '_>, proto: Object<'gc>, fn_proto: Object<'gc>, ) -> Object<'gc> { let mut object = ScriptObject::object(gc_context, Some(proto)); with_text_field!( gc_context, object, Some(fn_proto), "toString" => |text_field: EditText<'gc>, _avm: &mut Avm1<'gc>, _context: &mut UpdateContext<'_, 'gc, '_>, _args| { Ok(text_field.path().into()) }, "getNewTextFormat" => |text_field: EditText<'gc>, avm: &mut Avm1<'gc>, context: &mut UpdateContext<'_, 'gc, '_>, _args| { let tf = text_field.new_text_format(); Ok(tf.as_avm1_object(avm, context)?.into()) }, "setNewTextFormat" => |text_field: EditText<'gc>, avm: &mut Avm1<'gc>, context: &mut UpdateContext<'_, 'gc, '_>, args: &[Value<'gc>]| { let tf = args.get(0).cloned().unwrap_or(Value::Undefined); if let Value::Object(tf) = tf { let tf_parsed = TextFormat::from_avm1_object(tf, avm, context)?; text_field.set_new_text_format(tf_parsed, context.gc_context); } Ok(Value::Undefined.into()) } ); object.into() } pub fn attach_virtual_properties<'gc>(gc_context: MutationContext<'gc, '_>, object: Object<'gc>) { object.add_property( gc_context, "text", Executable::Native(get_text), Some(Executable::Native(set_text)), DontDelete | ReadOnly | DontEnum, ); object.add_property( gc_context, "textWidth", Executable::Native(text_width), None, ReadOnly.into(), ); object.add_property( gc_context, "textHeight", Executable::Native(text_height), None, ReadOnly.into(), ); object.add_property( gc_context, "multiline", Executable::Native(multiline), Some(Executable::Native(set_multiline)), ReadOnly.into(), ); object.add_property( gc_context, "wordWrap", Executable::Native(word_wrap), Some(Executable::Native(set_word_wrap)), ReadOnly.into(), ); }
pub fn constructor<'gc>( _avm: &mut Avm1<'gc>, _context: &mut UpdateContext<'_, 'gc, '_>, _this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { Ok(Value::Undefined.into()) }
function_block-full_function
[ { "content": "#[test]\n\nfn test_stage_object_enumerate() -> Result<(), Error> {\n\n let trace_log = run_swf(\"tests/swfs/avm1/stage_object_enumerate/test.swf\", 1)?;\n\n let mut actual: Vec<String> = trace_log.lines().map(|s| s.to_string()).collect();\n\n let mut expected = vec![\"clip1\", \"clip2\", ...
Rust
src/baseline/map.rs
rodrigo-bruno/dora
3c86c8d5ff7be52846f57fbaf46a047bf9c854b1
use std::cmp::Ordering; use std::collections::BTreeMap; use baseline::fct::JitFctId; use ctxt::SemContext; pub struct CodeMap { tree: BTreeMap<CodeSpan, CodeDescriptor>, } impl CodeMap { pub fn new() -> CodeMap { CodeMap { tree: BTreeMap::new(), } } pub fn dump(&self, ctxt: &SemContext) { println!("CodeMap {{"); for (key, data) in &self.tree { print!(" {:?} - {:?} => ", key.start, key.end); match data { &CodeDescriptor::DoraFct(jit_fct_id) => { let jit_fct = ctxt.jit_fcts[jit_fct_id].borrow(); let fct = ctxt.fcts[jit_fct.fct_id()].borrow(); println!("dora {}", fct.full_name(ctxt)); } &CodeDescriptor::CompilerThunk => println!("compiler_thunk"), &CodeDescriptor::ThrowThunk => println!("throw_thunk"), &CodeDescriptor::TrapThunk => println!("trap_thunk"), &CodeDescriptor::AllocThunk => println!("alloc_thunk"), &CodeDescriptor::NativeThunk(jit_fct_id) => { let jit_fct = ctxt.jit_fcts[jit_fct_id].borrow(); let fct = ctxt.fcts[jit_fct.fct_id()].borrow(); println!("native {}", fct.full_name(ctxt)); } &CodeDescriptor::DoraEntry => println!("dora_entry"), } } println!("}}"); } pub fn insert(&mut self, start: *const u8, end: *const u8, data: CodeDescriptor) { let span = CodeSpan::new(start, end); assert!(self.tree.insert(span, data).is_none()); } pub fn get(&self, ptr: *const u8) -> Option<CodeDescriptor> { let span = CodeSpan::new(ptr, unsafe { ptr.offset(1) }); self.tree.get(&span).map(|el| *el) } } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum CodeDescriptor { DoraFct(JitFctId), CompilerThunk, ThrowThunk, TrapThunk, AllocThunk, NativeThunk(JitFctId), DoraEntry, } #[derive(Copy, Clone, Debug)] struct CodeSpan { start: *const u8, end: *const u8, } impl CodeSpan { fn intersect(&self, other: &CodeSpan) -> bool { (self.start <= other.start && other.start < self.end) || (self.start < other.end && other.end <= self.end) || (other.start <= self.start && self.end <= other.end) } } impl PartialEq for CodeSpan { fn eq(&self, other: &CodeSpan) -> bool { self.intersect(other) } } impl Eq for CodeSpan {} impl PartialOrd for CodeSpan { fn partial_cmp(&self, other: &CodeSpan) -> Option<Ordering> { Some(self.cmp(other)) } } impl Ord for CodeSpan { fn cmp(&self, other: &CodeSpan) -> Ordering { if self.intersect(other) { Ordering::Equal } else if self.start >= other.end { Ordering::Greater } else { Ordering::Less } } } impl CodeSpan { fn new(start: *const u8, end: *const u8) -> CodeSpan { assert!(start < end); CodeSpan { start: start, end: end, } } } #[test] #[should_panic] fn test_new_fail() { span(7, 5); } #[test] fn test_new() { span(5, 7); } #[test] fn test_intersect() { assert!(span(5, 7).intersect(&span(1, 6))); assert!(!span(5, 7).intersect(&span(1, 5))); assert!(span(5, 7).intersect(&span(5, 7))); assert!(span(5, 7).intersect(&span(4, 7))); assert!(!span(5, 7).intersect(&span(7, 9))); assert!(!span(5, 7).intersect(&span(7, 8))); } #[cfg(test)] fn span(v1: usize, v2: usize) -> CodeSpan { CodeSpan::new(ptr(v1), ptr(v2)) } #[cfg(test)] pub fn ptr(val: usize) -> *const u8 { val as *const u8 } #[cfg(test)] mod tests { use super::*; #[test] fn test_insert() { let mut map = CodeMap::new(); map.insert(ptr(5), ptr(7), CodeDescriptor::DoraFct(1.into())); map.insert(ptr(7), ptr(9), CodeDescriptor::DoraFct(2.into())); assert_eq!(None, map.get(ptr(4))); assert_eq!(Some(CodeDescriptor::DoraFct(1.into())), map.get(ptr(5))); assert_eq!(Some(CodeDescriptor::DoraFct(1.into())), map.get(ptr(6))); assert_eq!(Some(CodeDescriptor::DoraFct(2.into())), map.get(ptr(7))); assert_eq!(Some(CodeDescriptor::DoraFct(2.into())), map.get(ptr(8))); assert_eq!(None, map.get(ptr(9))); } #[test] #[should_panic] fn test_insert_fails() { let mut map = CodeMap::new(); map.insert(ptr(5), ptr(7), CodeDescriptor::DoraFct(1.into())); map.insert(ptr(6), ptr(7), CodeDescriptor::DoraFct(2.into())); } }
use std::cmp::Ordering; use std::collections::BTreeMap; use baseline::fct::JitFctId; use ctxt::SemContext; pub struct CodeMap { tree: BTreeMap<CodeSpan, CodeDescriptor>, } impl CodeMap { pub fn new() -> CodeMap { CodeMap { tree: BTreeMap::new(), } } pub fn dump(&self, ctxt: &SemContext) { println!("CodeMap {{"); for (key, data) in &self.tree { print!(" {:?} - {:?} => ", key.start, key.end); match data { &CodeDescriptor::DoraFct(jit_fct_id) => { let jit_fct = ctxt.jit_fcts[jit_fct_id].borrow(); let fct = ctxt.fcts[jit_fct.fct_id()].borrow(); println!("dora {}", fct.full_name(ctxt)); } &CodeDescriptor::CompilerThunk => println!("compiler_thunk"), &CodeDescriptor::ThrowThunk => println!("throw_thunk"), &CodeDescriptor::TrapThunk => println!("trap_thunk"), &CodeDescriptor::AllocThunk => println!("alloc_thunk"), &CodeDescriptor::NativeThunk(jit_fct_id) => { let jit_fct = ctxt.jit_fcts[jit_fct_id].borrow(); let fct = ctxt.fcts[jit_fct.fct_id()].borrow(); println!("native {}", fct.full_name(ctxt)); } &CodeDescriptor::DoraEntry => println!("dora_entry"), } } println!("}}"); } pub fn insert(&mut self, start: *const u8, end: *const u8, data: CodeDescriptor) { let span = CodeSpan::new(start, end); assert!(self.tree.insert(span, data).is_none()); } pub fn get(&self, ptr: *const u8) -> Option<CodeDescriptor> { let span = CodeSpan::new(ptr, unsafe { ptr.offset(1) }); self.tree.get(&span).map(|el| *el) } } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum CodeDescriptor { DoraFct(JitFctId), CompilerThunk, ThrowThunk, TrapThunk, AllocThunk, NativeThunk(JitFctId), DoraEntry, } #[derive(Copy, Clone, Debug)] struct CodeSpan { start: *const u8, end: *const u8, } impl CodeSpan { fn intersect(&self, other: &CodeSpan) -> bool { (self.start <= other.start && other.start < self.end) || (self.start < other.end && other.end <= self.end) || (other.start <= self.start && self.end <= other.end) } } impl PartialEq for CodeSpan { fn eq(&self, other: &CodeSpan) -> bool { self.intersect(other) } } impl Eq for CodeSpan {} impl PartialOrd for CodeSpan { fn partial_cmp(&self, other: &CodeSpan) -> Option<Ordering> { Some(self.cmp(other)) } } impl Ord for CodeSpan { fn cmp(&self, other: &CodeSpan) -> Ordering { if self.intersect(other) { Ordering::Equal } else if self.start >= other.end { Ordering::Greater } else { Ordering::Less } } } impl CodeSpan {
} #[test] #[should_panic] fn test_new_fail() { span(7, 5); } #[test] fn test_new() { span(5, 7); } #[test] fn test_intersect() { assert!(span(5, 7).intersect(&span(1, 6))); assert!(!span(5, 7).intersect(&span(1, 5))); assert!(span(5, 7).intersect(&span(5, 7))); assert!(span(5, 7).intersect(&span(4, 7))); assert!(!span(5, 7).intersect(&span(7, 9))); assert!(!span(5, 7).intersect(&span(7, 8))); } #[cfg(test)] fn span(v1: usize, v2: usize) -> CodeSpan { CodeSpan::new(ptr(v1), ptr(v2)) } #[cfg(test)] pub fn ptr(val: usize) -> *const u8 { val as *const u8 } #[cfg(test)] mod tests { use super::*; #[test] fn test_insert() { let mut map = CodeMap::new(); map.insert(ptr(5), ptr(7), CodeDescriptor::DoraFct(1.into())); map.insert(ptr(7), ptr(9), CodeDescriptor::DoraFct(2.into())); assert_eq!(None, map.get(ptr(4))); assert_eq!(Some(CodeDescriptor::DoraFct(1.into())), map.get(ptr(5))); assert_eq!(Some(CodeDescriptor::DoraFct(1.into())), map.get(ptr(6))); assert_eq!(Some(CodeDescriptor::DoraFct(2.into())), map.get(ptr(7))); assert_eq!(Some(CodeDescriptor::DoraFct(2.into())), map.get(ptr(8))); assert_eq!(None, map.get(ptr(9))); } #[test] #[should_panic] fn test_insert_fails() { let mut map = CodeMap::new(); map.insert(ptr(5), ptr(7), CodeDescriptor::DoraFct(1.into())); map.insert(ptr(6), ptr(7), CodeDescriptor::DoraFct(2.into())); } }
fn new(start: *const u8, end: *const u8) -> CodeSpan { assert!(start < end); CodeSpan { start: start, end: end, } }
function_block-full_function
[ { "content": "pub fn should_emit_debug(ctxt: &SemContext, fct: &Fct) -> bool {\n\n if let Some(ref dbg_names) = ctxt.args.flag_emit_debug {\n\n fct_pattern_match(ctxt, fct, dbg_names)\n\n } else {\n\n false\n\n }\n\n}\n\n\n", "file_path": "src/baseline/codegen.rs", "rank": 0, ...
Rust
src/index/metadata.rs
kanbaru/kyoku
2760d80b3f7054c4c13bdaeb8ad7fb3e4d336e02
#[derive(Debug, PartialEq)] pub enum AudioFormat { FLAC, } #[derive(Debug, PartialEq, Clone)] pub struct AudioMetadata { pub name: String, pub number: u32, pub duration: u32, pub album: String, pub album_artist: String, pub artists: Vec<String>, pub picture: Option<Picture>, pub path: std::path::PathBuf, pub year: Option<i32>, pub lossless: bool, } #[derive(Debug, PartialEq, Clone)] pub struct Picture { pub bytes: Vec<u8>, } use sqlx::Sqlite; pub fn get_filetype(path: &std::path::PathBuf) -> Option<AudioFormat> { let extension = match path.extension() { Some(e) => e, _ => return None, }; let extension = match extension.to_str() { Some(e) => e, _ => return None, }; match extension.to_lowercase().as_str() { "flac" => Some(AudioFormat::FLAC), _ => None, } } pub async fn scan_file(path: &std::path::PathBuf, pool: sqlx::Pool<Sqlite>) { let data = match get_filetype(path) { Some(AudioFormat::FLAC) => Some(scan_flac(path, pool).await), None => return, }; match data { r => println!("{}", r.unwrap()), }; } pub async fn scan_flac(path: &std::path::PathBuf, pool: sqlx::Pool<Sqlite>) -> String { let tag = metaflac::Tag::read_from_path(path).unwrap(); let vorbis = tag.vorbis_comments().ok_or(0).unwrap(); let mut streaminfo = tag.get_blocks(metaflac::BlockType::StreamInfo); let duration = match streaminfo.next() { Some(&metaflac::Block::StreamInfo(ref s)) => { Some((s.total_samples as u32 / s.sample_rate) as u32) } _ => None, } .unwrap(); let year = vorbis.get("DATE").and_then(|d| d[0].parse::<i32>().ok()); let picture = tag .pictures() .filter(|&pic| matches!(pic.picture_type, metaflac::block::PictureType::CoverFront)) .next() .and_then(|pic| { Some(Picture { bytes: pic.data.to_owned(), }) }); let metadata = AudioMetadata { name: vorbis.title().map(|v| v[0].clone()).unwrap(), number: vorbis.track().unwrap(), duration: duration, album: vorbis.album().map(|v| v[0].clone()).unwrap(), album_artist: match vorbis.album_artist().map(|v| v[0].clone()) { Some(e) => e, None => vorbis.artist().map(|v| v[0].clone()).unwrap(), }, artists: vorbis.artist().unwrap().to_owned(), picture: picture, path: path.to_owned(), year: year, lossless: true, }; crate::index::db::add_song(metadata, pool).await; let secs = chrono::Duration::seconds(duration as i64); let mut formatted_duration = format!( "{}:{:02}", &secs.num_minutes(), &secs.num_seconds() - (secs.num_minutes() * 60) ); if secs.num_hours() > 0 { formatted_duration = format!( "{}:{:02}:{:02}", secs.num_hours(), &secs.num_minutes(), &secs.num_seconds() - (secs.num_minutes() * 60) ) } format!( "{}. {} by {} ({})", match vorbis.track() { Some(e) => e, None => 1, }, vorbis.title().map(|v| v[0].clone()).unwrap(), match vorbis.album_artist().map(|v| v[0].clone()) { Some(e) => e, None => vorbis.artist().map(|v| v[0].clone()).unwrap(), }, formatted_duration ) }
#[derive(Debug, PartialEq)] pub enum AudioFormat { FLAC, } #[derive(Debug, PartialEq, Clone)] pub struct AudioMetadata { pub name: String, pub number: u32, pub duration: u32, pub album: String, pub album_artist: String, pub artists: Vec<String>
.artist().map(|v| v[0].clone()).unwrap(), }, artists: vorbis.artist().unwrap().to_owned(), picture: picture, path: path.to_owned(), year: year, lossless: true, }; crate::index::db::add_song(metadata, pool).await; let secs = chrono::Duration::seconds(duration as i64); let mut formatted_duration = format!( "{}:{:02}", &secs.num_minutes(), &secs.num_seconds() - (secs.num_minutes() * 60) ); if secs.num_hours() > 0 { formatted_duration = format!( "{}:{:02}:{:02}", secs.num_hours(), &secs.num_minutes(), &secs.num_seconds() - (secs.num_minutes() * 60) ) } format!( "{}. {} by {} ({})", match vorbis.track() { Some(e) => e, None => 1, }, vorbis.title().map(|v| v[0].clone()).unwrap(), match vorbis.album_artist().map(|v| v[0].clone()) { Some(e) => e, None => vorbis.artist().map(|v| v[0].clone()).unwrap(), }, formatted_duration ) }
, pub picture: Option<Picture>, pub path: std::path::PathBuf, pub year: Option<i32>, pub lossless: bool, } #[derive(Debug, PartialEq, Clone)] pub struct Picture { pub bytes: Vec<u8>, } use sqlx::Sqlite; pub fn get_filetype(path: &std::path::PathBuf) -> Option<AudioFormat> { let extension = match path.extension() { Some(e) => e, _ => return None, }; let extension = match extension.to_str() { Some(e) => e, _ => return None, }; match extension.to_lowercase().as_str() { "flac" => Some(AudioFormat::FLAC), _ => None, } } pub async fn scan_file(path: &std::path::PathBuf, pool: sqlx::Pool<Sqlite>) { let data = match get_filetype(path) { Some(AudioFormat::FLAC) => Some(scan_flac(path, pool).await), None => return, }; match data { r => println!("{}", r.unwrap()), }; } pub async fn scan_flac(path: &std::path::PathBuf, pool: sqlx::Pool<Sqlite>) -> String { let tag = metaflac::Tag::read_from_path(path).unwrap(); let vorbis = tag.vorbis_comments().ok_or(0).unwrap(); let mut streaminfo = tag.get_blocks(metaflac::BlockType::StreamInfo); let duration = match streaminfo.next() { Some(&metaflac::Block::StreamInfo(ref s)) => { Some((s.total_samples as u32 / s.sample_rate) as u32) } _ => None, } .unwrap(); let year = vorbis.get("DATE").and_then(|d| d[0].parse::<i32>().ok()); let picture = tag .pictures() .filter(|&pic| matches!(pic.picture_type, metaflac::block::PictureType::CoverFront)) .next() .and_then(|pic| { Some(Picture { bytes: pic.data.to_owned(), }) }); let metadata = AudioMetadata { name: vorbis.title().map(|v| v[0].clone()).unwrap(), number: vorbis.track().unwrap(), duration: duration, album: vorbis.album().map(|v| v[0].clone()).unwrap(), album_artist: match vorbis.album_artist().map(|v| v[0].clone()) { Some(e) => e, None => vorbis
random
[ { "content": "CREATE TABLE `album` (\n\n `id` integer primary key autoincrement,\n\n `name` varchar(255) not null,\n\n `artist` integet not null,\n\n `picture` varchar(255),\n\n `year` integer,\n\n `created_at` datetime not null,\n\n `updated_at` datetime,\n\n FOREIGN KEY (`artist`) REFERENCES `artist` ...
Rust
src/ui.rs
PurpleBooth/fast-conventional
3b95bf0625b95f3d6a8ff8b8f407dd8fad5633dd
use crate::models::ConventionalChange; use crate::models::ConventionalCommit; use crate::models::ConventionalScope; use inquire::{Editor, Select, Text}; use miette::IntoDiagnostic; use miette::Result; use mit_commit::CommitMessage; use super::models::fast_conventional_config::FastConventionalConfig; use super::models::{ConventionalBody, ConventionalSubject}; pub fn prompt_body(previous_body: &ConventionalBody) -> Result<Option<String>> { let mut body_ui = Editor::new("description") .with_file_extension("COMMIT_EDITMSG") .with_predefined_text(&previous_body.0) .with_help_message("A body (if any)"); body_ui = if previous_body.is_empty() { body_ui } else { body_ui.with_predefined_text(&previous_body.0) }; Ok(body_ui .prompt_skippable() .into_diagnostic()? .filter(|breaking_message| !breaking_message.is_empty())) } pub fn prompt_subject(previous_subject: &ConventionalSubject) -> Result<String> { let mut subject_ui = Text::new("subject") .with_help_message("Summary of the code changes") .with_validator(&|subject: &str| { if subject.is_empty() { Err("subject can't be empty".to_string()) } else { Ok(()) } }); subject_ui = if previous_subject.is_empty() { subject_ui } else { subject_ui.with_default(&previous_subject.0) }; subject_ui.prompt().into_diagnostic() } pub fn prompt_breaking(previous_breaking: &str) -> Result<Option<String>> { let mut breaking_ui = Text::new("breaking").with_help_message("Did the public interface change?"); if !previous_breaking.is_empty() { breaking_ui = breaking_ui.with_default(previous_breaking); } let breaking: Option<String> = breaking_ui .prompt_skippable() .into_diagnostic()? .filter(|breaking_message| !breaking_message.is_empty()); Ok(breaking) } pub fn prompt_commit_scope( config: &FastConventionalConfig, scope_index: usize, ) -> Result<Option<String>> { if config.get_scopes().is_empty() { Ok(None) } else { let scopes = config.get_scopes(); Ok(Select::new("scope", scopes.into_iter().collect()) .with_help_message("What scope your change is within (if any)?") .with_starting_cursor(scope_index) .prompt_skippable() .into_diagnostic()? .filter(|scope| !scope.is_empty())) } } pub fn prompt_commit_type(config: &FastConventionalConfig, type_index: usize) -> Result<String> { Select::new( "type", config.get_types().into_iter().collect::<Vec<String>>(), ) .with_help_message("What type of change is this?") .with_starting_cursor(type_index) .prompt() .into_diagnostic() } pub fn ask_user( config: &FastConventionalConfig, conventional_commit: Option<ConventionalCommit>, ) -> Result<ConventionalCommit> { let (type_index, scope_index, previous_breaking, previous_subject, previous_body) = conventional_commit .map(|conv| { ( conv.type_index(config.get_types().into_iter().collect::<Vec<_>>()), conv.scope_index(config.get_scopes().into_iter().collect::<Vec<_>>()), match conv.breaking { ConventionalChange::BreakingWithMessage(message) => message, ConventionalChange::Compatible => "".to_string(), ConventionalChange::BreakingWithoutMessage => "See description".to_string(), }, conv.subject, conv.body, ) }) .unwrap_or_default(); let commit_type: String = prompt_commit_type(config, type_index)?; let scope: Option<String> = prompt_commit_scope(config, scope_index)?; let breaking = prompt_breaking(&previous_breaking)?; let subject = prompt_subject(&previous_subject)?; let body = prompt_body(&previous_body)?; Ok(ConventionalCommit { type_slug: commit_type.into(), scope: scope.map(ConventionalScope::from), breaking: breaking.into(), subject: subject.into(), body: body.into(), }) } pub fn ask_fallback(previous_text: &'_ str) -> Result<CommitMessage<'_>> { Ok(Editor::new("Non-conventional editor.rs") .with_file_extension("COMMIT_EDITMSG") .with_predefined_text(previous_text) .with_help_message("This commit isn't conventional") .prompt() .into_diagnostic()? .into()) }
use crate::models::ConventionalChange; use crate::models::ConventionalCommit; use crate::models::ConventionalScope; use inquire::{Editor, Select, Text}; use miette::IntoDiagnostic; use miette::Result; use mit_commit::CommitMessage; use super::models::fast_conventional_config::FastConventionalConfig; use super::models::{ConventionalBody, ConventionalSubject}; pub fn prompt_body(previous_body: &ConventionalBody) -> Result<Option<String>> { let mut body_ui = Editor::new("description") .with_file_extension("COMMIT_EDITMSG") .with_predefined_text(&previous_body.0) .with_help_message("A body (if any)"); body_ui = if previous_body.is_empty() { body_ui } else { body_ui.with_predefined_text(&previous_body.0) }; Ok(body_ui .prompt_skippable() .into_diagnostic()? .filter(|breaking_message| !breaking_message.is_empty())) } pub fn prompt_subject(previous_subject: &ConventionalSubject) -> Result<String> { let mut subject_ui = Text::new("subject") .with_help_message("Summary of the code changes") .with_validator(&|subject: &str| { if subject.is_empty() { Err("subject can't be empty".to_string()) } else { Ok(()) } }); subject_ui = if previous_subject.is_empty() { subject_ui } else { subject_ui.with_default(&previous_subject.0) }; subject_ui.prompt().into_diagnostic() } pub fn prompt_breaking(previous_breaking: &str) -> Result<Option<String>> { let mut breaking_ui = Text::new("breaking").with_help_message("Did the public interface change?"); if !previous_breaking.is_empty() { breaking_ui = breaking_ui.with_default(previous_breaking); } let breaking: Option<String> = breaking_ui .prompt_skippable() .into_diagnostic()? .filter(|breaking_message| !breaking_message.is_empty()); Ok(breaking) } pub fn prompt_commit_scope( config: &FastConventionalConfig, scope_index: usize, ) -> Result<Option<String>> { if config.get_scopes().is_empty() { Ok(None) } else { let scopes = config.get_scopes(); Ok(Select::new("scope", scopes.into_iter().collect()) .with_help_message("What scope your change is within (if any)?") .with_starting_cursor(scope_index) .prompt_skippable() .into_diagnostic()? .filter(|scope| !scope.is_empty())) } } pub fn prompt_commit_type(config: &FastConventionalConfig, type_index: usize) -> Result<String> { Select::new( "type", config.get_types().into_iter().collect::<Vec<String>>(), ) .with_help_message("What type of change is this?") .with_starting_cursor(type_index) .prompt() .into_diagnostic() } pub fn ask_user( config: &FastConventionalConfig, conventional_commit: Option<ConventionalCommit>, ) -> Result<ConventionalCommit> { let (type_index, scope_index, previous_breaking, previous_subject, previous_body) = conventional_commit .map(|conv| { ( conv.type_index(config.get_types().into_iter().collect::<Vec<_>>()), conv.scope_index(config.get_scopes().into_iter().collect::<Vec<_>>()), match conv.breaking { ConventionalChange::BreakingWithMessage(message) => message, ConventionalChange::Compatible => "".to_string(), ConventionalChange::BreakingWithoutMessa
pub fn ask_fallback(previous_text: &'_ str) -> Result<CommitMessage<'_>> { Ok(Editor::new("Non-conventional editor.rs") .with_file_extension("COMMIT_EDITMSG") .with_predefined_text(previous_text) .with_help_message("This commit isn't conventional") .prompt() .into_diagnostic()? .into()) }
ge => "See description".to_string(), }, conv.subject, conv.body, ) }) .unwrap_or_default(); let commit_type: String = prompt_commit_type(config, type_index)?; let scope: Option<String> = prompt_commit_scope(config, scope_index)?; let breaking = prompt_breaking(&previous_breaking)?; let subject = prompt_subject(&previous_subject)?; let body = prompt_body(&previous_body)?; Ok(ConventionalCommit { type_slug: commit_type.into(), scope: scope.map(ConventionalScope::from), breaking: breaking.into(), subject: subject.into(), body: body.into(), }) }
function_block-function_prefixed
[ { "content": "pub fn run(commit_message_path: PathBuf, config_path: PathBuf) -> Result<()> {\n\n let buf: PathBuf = commit_message_path;\n\n let config: FastConventionalConfig = config_path.try_into()?;\n\n let existing_contents = fs::read_to_string(buf.clone()).into_diagnostic()?;\n\n let existing_...
Rust
kubeless/src/lib.rs
Slowki/kubeless.rs
6fb14b3f14ed4673cef8a9e07fded2d790f277b1
extern crate actix_web; extern crate bytes; extern crate futures; #[macro_use] extern crate prometheus; #[macro_use] extern crate lazy_static; use actix_web::http::Method; use actix_web::{server, App, AsyncResponder, HttpMessage, HttpRequest, HttpResponse, Responder}; use futures::{Future, Stream}; use prometheus::Encoder; pub mod types; pub use types::*; pub const DEFAULT_TIMEOUT: usize = 180; pub const DEFAULT_MEMORY_LIMIT: usize = 0; lazy_static! { pub static ref FUNC_HANDLER : String = std::env::var("FUNC_HANDLER").expect("the FUNC_HANDLER environment variable must be provided"); static ref FUNC_TIMEOUT : usize = match std::env::var("FUNC_TIMEOUT") { Ok(timeout_str) => timeout_str.parse::<usize>().unwrap_or(DEFAULT_TIMEOUT), Err(_) => DEFAULT_TIMEOUT, }; static ref FUNC_RUNTIME : String = std::env::var("FUNC_RUNTIME").unwrap_or_else(|_| String::new()); static ref FUNC_MEMORY_LIMIT : usize = match std::env::var("FUNC_MEMORY_LIMIT") { Ok(mem_limit_str) => mem_limit_str.parse::<usize>().unwrap_or(DEFAULT_MEMORY_LIMIT), Err(_) => DEFAULT_MEMORY_LIMIT, }; static ref CALL_HISTOGRAM : prometheus::Histogram = register_histogram!(histogram_opts!("function_duration_seconds", "Duration of user function in seconds")).unwrap(); static ref CALL_TOTAL : prometheus::Counter = register_counter!(opts!("function_calls_total", "Number of calls to user function")).unwrap(); static ref FAILURES_TOTAL : prometheus::Counter = register_counter!(opts!("function_failures_total", "Number of failed calls")).unwrap(); static ref REGISTRY : prometheus::Registry = { let reg = prometheus::Registry::new(); reg.register(Box::new(CALL_HISTOGRAM.clone())).unwrap(); reg.register(Box::new(CALL_TOTAL.clone())).unwrap(); reg.register(Box::new(FAILURES_TOTAL.clone())).unwrap(); reg }; } #[macro_export] macro_rules! select_function { ( $( $x:ident ),* ) => { { use kubeless::types::UserFunction; use kubeless::FUNC_HANDLER; let selected_function : Option<UserFunction> = [$((stringify!($x), $x as UserFunction), )*].iter().find(|x| x.0 == *FUNC_HANDLER).map(|x| x.1); match selected_function { Some(result) => result, None => { let mut available_functions = String::new(); $( if available_functions.len() > 0 { available_functions.push_str(", "); } available_functions.push_str(stringify!($x)); )* panic!("No function named {} available, available functions are: {}", *FUNC_HANDLER, available_functions) } } } }; } fn handle_request( req: HttpRequest, user_function: UserFunction, ) -> Box<Future<Item = HttpResponse, Error = actix_web::Error>> { let get_header = |req: &HttpRequest, header_name: &str| match req.headers().get(header_name) { Some(header) => header .to_str() .map(String::from) .unwrap_or_else(|_| String::new()), None => String::new(), }; let event_id = get_header(&req, "event-id"); let event_type = get_header(&req, "event-type"); let event_time = get_header(&req, "event-time"); let event_namespace = get_header(&req, "event-namespace"); let body_future: Box<Future<Item = Option<bytes::Bytes>, Error = actix_web::Error>> = if req.method() == &Method::POST { Box::new( req.concat2() .from_err() .map(Some), ) } else { Box::new(futures::future::ok::<Option<bytes::Bytes>, actix_web::Error>(None)) }; body_future .map(move |data: Option<bytes::Bytes>| { CALL_TOTAL.inc(); let timer = CALL_HISTOGRAM.start_timer(); let call_event = Event { data, event_id, event_type, event_time, event_namespace, }; let call_context = Context { function_name: FUNC_HANDLER.clone(), runtime: FUNC_RUNTIME.clone(), timeout: *FUNC_TIMEOUT, memory_limit: *FUNC_MEMORY_LIMIT, }; let result = std::panic::catch_unwind(move || user_function(call_event, call_context)); timer.observe_duration(); match result { Ok(result) => HttpResponse::Ok().body(result), Err(reason) => { FAILURES_TOTAL.inc(); let body: &str = match reason.downcast_ref::<String>() { Some(err_string) => err_string.as_str(), None => "Unknown error", }; HttpResponse::InternalServerError().body(body.to_string()) } } }) .responder() } fn healthz(req: HttpRequest) -> impl Responder { match *req.method() { Method::GET | Method::HEAD => HttpResponse::Ok().content_type("plain/text").body("OK"), _ => HttpResponse::BadRequest().body("Bad Request"), } } fn metrics(req: HttpRequest) -> impl Responder { match *req.method() { Method::GET | Method::HEAD => { let mut buffer = vec![]; prometheus::TextEncoder::new().encode(&REGISTRY.gather(), &mut buffer).unwrap(); HttpResponse::Ok().content_type("plain/text").body(String::from_utf8(buffer).unwrap()) }, _ => HttpResponse::BadRequest().body("Bad Request"), } } pub fn start(func: UserFunction) { let port = std::env::var("FUNC_PORT").unwrap_or_else(|_| String::from("8080")); server::new(move || { App::new() .resource("/", move |r| r.f(move |req| handle_request(req, func))) .resource("/healthz", |r| r.f(healthz)) .resource("/metrics", |r| r.f(metrics)) }).bind(format!("127.0.0.1:{}", &port)) .unwrap_or_else(|_| panic!("Can not bind to port {}", &port)) .run(); }
extern crate actix_web; extern crate bytes; extern crate futures; #[macro_use] extern crate prometheus; #[macro_use] extern crate lazy_static; use actix_web::http::Method; use actix_web::{server, App, AsyncResponder, HttpMessage, HttpRequest, HttpResponse, Responder}; use futures::{Future, Stream}; use prometheus::Encoder; pub mod types; pub use types::*; pub const DEFAULT_TIMEOUT: usize = 180; pub const DEFAULT_MEMORY_LIMIT: usize = 0; lazy_static! { pub static ref FUNC_HANDLER : String = std::env::var("FUNC_HANDLER").expect("the FUNC_HANDLER environment variable must be provided"); static ref FUNC_TIMEOUT : usize = match std::env::var("FUNC_TIMEOUT") { Ok(timeout_str) => timeout_str.parse::<usize>().unwrap_or(DEFAULT_TIMEOUT), Err(_) => DEFAULT_TIMEOUT, }; static ref FUNC_RUNTIME : String = std::env::var("FUNC_RUNTIME").unwrap_or_else(|_| String::new()); static ref FUNC_MEMORY_LIMIT : usize = match std::env::var("FUNC_MEMORY_LIMIT") { Ok(mem_limit_str) => mem_limit_str.parse::<usize>().unwrap_or(DEFAULT_MEMORY_LIMIT), Err(_) => DEFAULT_MEMORY_LIMIT, }; static ref CALL_HISTOGRAM : prometheus::Histogram = register_histogram!(histogram_opts!("function_duration_seconds", "Duration of user function in seconds")).unwrap(); static ref CALL_TOTAL : prometheus::Counter = register_counter!(opts!("function_calls_total", "Number of calls to user function")).unwrap(); static ref FAILURES_TOTAL : prometheus::Counter = register_counter!(opts!("function_failures_total", "Number of failed calls")).unwrap(); static ref REGISTRY : prometheus::Registry = { let reg = prometheus::Registry::new(); reg.register(Box::new(CALL_HISTOGRAM.clone())).unwrap(); reg.register(Box::new(CALL_TOTAL.clone())).unwrap(); reg.register(Box::new(FAILURES_TOTAL.clone())).unwrap(); reg }; } #[macro_export] macro_rules! select_function { ( $( $x:ident ),* ) => { { use kubeless::types::UserFunction; use kubeless::FUNC_HANDLER; let selected_function : Option<UserFunction> = [$((stringify!($x), $x as UserFunction), )*].iter().find(|x| x.0 == *FUNC_HANDLER).map(|x| x.1); match selected_function { Some(result) => result, None => { let mut available_functions = String::new(); $( if available_functions.len() > 0 { available_functions.push_str(", "); } available_functions.push_str(stringify!($x)); )* panic!("No function named {} available, available functions are: {}", *FUNC_HANDLER, available_functions) } } } }; } fn handle_request( req: HttpRequest, user_function: UserFunction, ) -> Box<Future<Item = HttpResponse, Error = actix_web::Error>> { let get_header = |req: &HttpRequest, header_name: &str| match req.headers().get(header_name) { Some(header) => header .to_str() .map(String::from) .unwrap_or_else(|_| String::new()), None => String::new(), }; let event_id = get_header(&req, "event-id"); let event_type = get_header(&req, "event-type"); let event_time = get_header(&req, "event-time"); let event_namespace = get_header(&req, "event-namespace"); let body_future: Box<Future<Item = Option<bytes::Bytes>, Error = actix_web::Error>> = if req.method() == &Method::POST { Box::new( req.concat2() .from_err() .map(Some), ) } else { Box::new(futures::future::ok::<Option<bytes::Bytes>, actix_web::Error>(None)) }; body_future .map(move |data: Option<bytes::Bytes>| { CALL_TOTAL.inc(); let timer = CALL_HISTOGRAM.start_timer(); let call_event = Event { data, event_id, event_type, event_time, event_namespace, }; let call_context = Context { function_name: FUNC_HANDLER.clone(), runtime: FUNC_RUNTIME.clone(), timeout: *FUNC_TIMEOUT, memory_limit: *FUNC_MEMORY_LIMIT, }; let result = std::panic::catch_unwind(move || user_function(call_event, call_context)); timer.observe_duration(); match result { Ok(result) => HttpResponse::Ok().body(result), Err(reason) => { FAILURES_TOTAL.inc(); let body: &str = match reason.downcast_ref::<String>() { Some(err_string) => err_string.as_str(), None => "Unknown error", }; HttpResponse::InternalServerError().body(body.to_string()) } } }) .responder() } fn healthz(req: HttpRequest) -> impl Responder { match *req.method() { Method::GET | Method::HEAD => H
fn metrics(req: HttpRequest) -> impl Responder { match *req.method() { Method::GET | Method::HEAD => { let mut buffer = vec![]; prometheus::TextEncoder::new().encode(&REGISTRY.gather(), &mut buffer).unwrap(); HttpResponse::Ok().content_type("plain/text").body(String::from_utf8(buffer).unwrap()) }, _ => HttpResponse::BadRequest().body("Bad Request"), } } pub fn start(func: UserFunction) { let port = std::env::var("FUNC_PORT").unwrap_or_else(|_| String::from("8080")); server::new(move || { App::new() .resource("/", move |r| r.f(move |req| handle_request(req, func))) .resource("/healthz", |r| r.f(healthz)) .resource("/metrics", |r| r.f(metrics)) }).bind(format!("127.0.0.1:{}", &port)) .unwrap_or_else(|_| panic!("Can not bind to port {}", &port)) .run(); }
ttpResponse::Ok().content_type("plain/text").body("OK"), _ => HttpResponse::BadRequest().body("Bad Request"), } }
function_block-function_prefixed
[ { "content": "fn say_goodbye(event: kubeless::Event, ctx: kubeless::Context) -> String {\n\n match event.data {\n\n Some(name) => format!(\"Goodbye, {}\", String::from_utf8_lossy(&name)),\n\n None => String::from(\"Goodbye\"),\n\n }\n\n}\n\n\n", "file_path": "hello-kubeless/src/main.rs",...
Rust
src/github/mod.rs
dustlang/sync-team
f59aaa68e717e54b54d0b6a0fd5fb02bad14fe45
mod api; use self::api::{GitHub, TeamPrivacy, TeamRole}; use crate::TeamApi; use failure::Error; use log::{debug, info}; use std::collections::{HashMap, HashSet}; static DEFAULT_DESCRIPTION: &str = "Managed by the rust-lang/team repository."; static DEFAULT_PRIVACY: TeamPrivacy = TeamPrivacy::Closed; pub(crate) struct SyncGitHub { github: GitHub, teams: Vec<rust_team_data::v1::Team>, usernames_cache: HashMap<usize, String>, org_owners: HashMap<String, HashSet<usize>>, } impl SyncGitHub { pub(crate) fn new(token: String, team_api: &TeamApi, dry_run: bool) -> Result<Self, Error> { let github = GitHub::new(token, dry_run); let teams = team_api.get_teams()?; debug!("caching mapping between user ids and usernames"); let users = teams .iter() .filter_map(|t| t.github.as_ref().map(|gh| &gh.teams)) .flat_map(|teams| teams) .flat_map(|team| &team.members) .copied() .collect::<HashSet<_>>(); let usernames_cache = github.usernames(&users.into_iter().collect::<Vec<_>>())?; debug!("caching organization owners"); let orgs = teams .iter() .filter_map(|t| t.github.as_ref()) .flat_map(|gh| &gh.teams) .map(|gh_team| &gh_team.org) .collect::<HashSet<_>>(); let mut org_owners = HashMap::new(); for org in &orgs { org_owners.insert((*org).to_string(), github.org_owners(&org)?); } Ok(SyncGitHub { github, teams, usernames_cache, org_owners, }) } pub(crate) fn synchronize_all(&self) -> Result<(), Error> { for team in &self.teams { if let Some(gh) = &team.github { for github_team in &gh.teams { self.synchronize(github_team)?; } } } Ok(()) } fn synchronize(&self, github_team: &rust_team_data::v1::GitHubTeam) -> Result<(), Error> { let slug = format!("{}/{}", github_team.org, github_team.name); debug!("synchronizing {}", slug); let team = match self.github.team(&github_team.org, &github_team.name)? { Some(team) => team, None => self.github.create_team( &github_team.org, &github_team.name, DEFAULT_DESCRIPTION, DEFAULT_PRIVACY, )?, }; if team.name != github_team.name || team.description != DEFAULT_DESCRIPTION || team.privacy != DEFAULT_PRIVACY { self.github.edit_team( &team, &github_team.name, DEFAULT_DESCRIPTION, DEFAULT_PRIVACY, )?; } let mut current_members = self.github.team_memberships(&team)?; for member in &github_team.members { let expected_role = self.expected_role(&github_team.org, *member); let username = &self.usernames_cache[member]; if let Some(member) = current_members.remove(&member) { if member.role != expected_role { info!( "{}: user {} has the role {} instead of {}, changing them...", slug, username, member.role, expected_role ); self.github.set_membership(&team, username, expected_role)?; } else { debug!("{}: user {} is in the correct state", slug, username); } } else { info!("{}: user {} is missing, adding them...", slug, username); self.github.set_membership(&team, username, expected_role)?; } } for member in current_members.values() { info!( "{}: user {} is not in the team anymore, removing them...", slug, member.username ); self.github.remove_membership(&team, &member.username)?; } Ok(()) } fn expected_role(&self, org: &str, user: usize) -> TeamRole { if let Some(true) = self .org_owners .get(org) .map(|owners| owners.contains(&user)) { TeamRole::Maintainer } else { TeamRole::Member } } }
mod api; use self::api::{GitHub, TeamPrivacy, TeamRole}; use crate::TeamApi; use failure::Error; use log::{debug, info}; use std::collections::{HashMap, HashSet}; static DEFAULT_DESCRIPTION: &str = "Managed by the rust-lang/team repository."; static DEFAULT_PRIVACY: TeamPrivacy = TeamPrivacy::Closed; pub(crate) struct SyncGitHub { github: GitHub, teams: Vec<rust_team_data::v1::Team>, usernames_cache: HashMap<usize, String>, org_owners: HashMap<String, HashSet<usize>>, } impl SyncGitHub { pub(crate) fn new(token: String, team_api: &TeamApi, dry_run: bool) -> Result<Self, Error> { let github = GitHub::new(token, dry_run); let teams = team_api.get_teams()?; debug!("caching mapping between user ids and usernames"); let users = teams .iter() .filter_map(|t| t.github.as_ref().map(|gh| &gh.teams)) .flat_map(|teams| teams) .flat_map(|team| &team.members) .copied() .collect::<HashSet<_>>(); let usernames_cache = github.usernames(&users.into_iter().collect::<Vec<_>>())?; debug!("caching organization owners"); let orgs = teams .iter() .filter_map(|t| t.github.as_ref()) .flat_map(|gh| &gh.teams) .map(|gh_team| &gh_team.org) .collect::<HashSet<_>>(); let mut org_owners = HashMap::new(); for org in &orgs { org_owners.insert((*org).to_string(), github.org_owners(&org)?); } Ok(SyncGitHub { github, teams, usernames_cache, org_owners, }) } pub(crate) fn synchronize_all(&self) -> Result<(), Error> { for team in &self.teams { if let Some(gh) = &team.github { for github_team in &gh.teams { self.synchronize(github_team)?; } } } Ok(()) } fn
github.team_memberships(&team)?; for member in &github_team.members { let expected_role = self.expected_role(&github_team.org, *member); let username = &self.usernames_cache[member]; if let Some(member) = current_members.remove(&member) { if member.role != expected_role { info!( "{}: user {} has the role {} instead of {}, changing them...", slug, username, member.role, expected_role ); self.github.set_membership(&team, username, expected_role)?; } else { debug!("{}: user {} is in the correct state", slug, username); } } else { info!("{}: user {} is missing, adding them...", slug, username); self.github.set_membership(&team, username, expected_role)?; } } for member in current_members.values() { info!( "{}: user {} is not in the team anymore, removing them...", slug, member.username ); self.github.remove_membership(&team, &member.username)?; } Ok(()) } fn expected_role(&self, org: &str, user: usize) -> TeamRole { if let Some(true) = self .org_owners .get(org) .map(|owners| owners.contains(&user)) { TeamRole::Maintainer } else { TeamRole::Member } } }
synchronize(&self, github_team: &rust_team_data::v1::GitHubTeam) -> Result<(), Error> { let slug = format!("{}/{}", github_team.org, github_team.name); debug!("synchronizing {}", slug); let team = match self.github.team(&github_team.org, &github_team.name)? { Some(team) => team, None => self.github.create_team( &github_team.org, &github_team.name, DEFAULT_DESCRIPTION, DEFAULT_PRIVACY, )?, }; if team.name != github_team.name || team.description != DEFAULT_DESCRIPTION || team.privacy != DEFAULT_PRIVACY { self.github.edit_team( &team, &github_team.name, DEFAULT_DESCRIPTION, DEFAULT_PRIVACY, )?; } let mut current_members = self.
function_block-random_span
[ { "content": "fn mangle_address(addr: &str) -> Result<String, Error> {\n\n // Escape dots since they have a special meaning in Python regexes\n\n let mangled = addr.replace(\".\", \"\\\\.\");\n\n\n\n // Inject (?:\\+.+)? before the '@' in the address to support '+' aliases like\n\n // infra+botname@...
Rust
tests/glyph_substitution_test.rs
stainless-steel/opentype
af2d93b7d5371b35e844d92c4d64a68f2b8428e0
extern crate opentype; extern crate truetype; use opentype::glyph_substitution::{GlyphSubstitution, SingleSubstitution, Table}; use opentype::layout::script::{Language, Script}; use truetype::Value; #[macro_use] mod common; #[test] fn features() { let GlyphSubstitution { features, .. } = ok!(Value::read(&mut setup!(SourceSerifPro, "GSUB"))); let tags = features .headers .iter() .map(|header| header.tag) .collect::<Vec<_>>(); #[rustfmt::skip] assert!( tags == tags![ b"aalt", b"aalt", b"aalt", b"aalt", b"aalt", b"case", b"case", b"case", b"case", b"case", b"dnom", b"dnom", b"dnom", b"dnom", b"dnom", b"frac", b"frac", b"frac", b"frac", b"frac", b"liga", b"liga", b"liga", b"liga", b"liga", b"lnum", b"lnum", b"lnum", b"lnum", b"lnum", b"locl", b"locl", b"locl", b"numr", b"numr", b"numr", b"numr", b"numr", b"onum", b"onum", b"onum", b"onum", b"onum", b"ordn", b"ordn", b"ordn", b"ordn", b"ordn", b"pnum", b"pnum", b"pnum", b"pnum", b"pnum", b"sinf", b"sinf", b"sinf", b"sinf", b"sinf", b"subs", b"subs", b"subs", b"subs", b"subs", b"sups", b"sups", b"sups", b"sups", b"sups", b"tnum", b"tnum", b"tnum", b"tnum", b"tnum", b"zero", b"zero", b"zero", b"zero", b"zero", ] ); let lookups = features .records .iter() .map(|record| record.lookup_count) .collect::<Vec<_>>(); #[rustfmt::skip] assert!( lookups == vec![ 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ] ); } #[test] fn lookups() { let GlyphSubstitution { lookups, .. } = ok!(Value::read(&mut setup!(SourceSerifPro, "GSUB"))); let kinds = lookups .records .iter() .map(|record| record.kind) .collect::<Vec<_>>(); assert!(kinds == &[1, 3, 1, 1, 1, 1, 1, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 1]); let record = &lookups.records[0]; assert!(record.tables.len() == 1); match &record.tables[0] { &Table::SingleSubstitution(SingleSubstitution::Format2(ref table)) => { assert!(table.glyph_count == 61); } _ => unreachable!(), } let record = &lookups.records[17]; assert!(record.tables.len() == 1); match &record.tables[0] { &Table::LigatureSubstitution(ref table) => { assert!(table.set_count == 1); let table = &table.sets[0]; assert!(table.count == 3); let table = &table.records[0]; assert!(table.component_count == 2); } _ => unreachable!(), } } #[test] fn scripts() { let GlyphSubstitution { scripts, .. } = ok!(Value::read(&mut setup!(SourceSerifPro, "GSUB"))); let tags = scripts .headers .iter() .map(|header| header.tag) .collect::<Vec<_>>(); assert!(tags == tags![b"DFLT", b"latn"]); assert!(scripts.get(Script::Default).is_some()); assert!(scripts.get(Script::Latin).is_some()); let tags = scripts .records .iter() .map(|record| { record .language_headers .iter() .map(|header| header.tag) .collect::<Vec<_>>() }) .collect::<Vec<_>>(); assert!(tags == &[vec![], tags![b"AZE ", b"CRT ", b"TRK "]]); let record = &scripts.records[0]; assert!(record.default_language.is_some()); assert!(record.language_count == 0); let record = &scripts.records[1]; assert!(record.language_count == 3); assert!(record.get(Language::Turkish).is_some()); }
extern crate opentype; extern crate truetype; use opentype::glyph_substitution::{GlyphSubstitution, SingleSubstitution, Table}; use opentype::layout::script::{Language, Script}; use truetype::Value; #[macro_use] mod common; #[test]
#[test] fn lookups() { let GlyphSubstitution { lookups, .. } = ok!(Value::read(&mut setup!(SourceSerifPro, "GSUB"))); let kinds = lookups .records .iter() .map(|record| record.kind) .collect::<Vec<_>>(); assert!(kinds == &[1, 3, 1, 1, 1, 1, 1, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 1]); let record = &lookups.records[0]; assert!(record.tables.len() == 1); match &record.tables[0] { &Table::SingleSubstitution(SingleSubstitution::Format2(ref table)) => { assert!(table.glyph_count == 61); } _ => unreachable!(), } let record = &lookups.records[17]; assert!(record.tables.len() == 1); match &record.tables[0] { &Table::LigatureSubstitution(ref table) => { assert!(table.set_count == 1); let table = &table.sets[0]; assert!(table.count == 3); let table = &table.records[0]; assert!(table.component_count == 2); } _ => unreachable!(), } } #[test] fn scripts() { let GlyphSubstitution { scripts, .. } = ok!(Value::read(&mut setup!(SourceSerifPro, "GSUB"))); let tags = scripts .headers .iter() .map(|header| header.tag) .collect::<Vec<_>>(); assert!(tags == tags![b"DFLT", b"latn"]); assert!(scripts.get(Script::Default).is_some()); assert!(scripts.get(Script::Latin).is_some()); let tags = scripts .records .iter() .map(|record| { record .language_headers .iter() .map(|header| header.tag) .collect::<Vec<_>>() }) .collect::<Vec<_>>(); assert!(tags == &[vec![], tags![b"AZE ", b"CRT ", b"TRK "]]); let record = &scripts.records[0]; assert!(record.default_language.is_some()); assert!(record.language_count == 0); let record = &scripts.records[1]; assert!(record.language_count == 3); assert!(record.get(Language::Turkish).is_some()); }
fn features() { let GlyphSubstitution { features, .. } = ok!(Value::read(&mut setup!(SourceSerifPro, "GSUB"))); let tags = features .headers .iter() .map(|header| header.tag) .collect::<Vec<_>>(); #[rustfmt::skip] assert!( tags == tags![ b"aalt", b"aalt", b"aalt", b"aalt", b"aalt", b"case", b"case", b"case", b"case", b"case", b"dnom", b"dnom", b"dnom", b"dnom", b"dnom", b"frac", b"frac", b"frac", b"frac", b"frac", b"liga", b"liga", b"liga", b"liga", b"liga", b"lnum", b"lnum", b"lnum", b"lnum", b"lnum", b"locl", b"locl", b"locl", b"numr", b"numr", b"numr", b"numr", b"numr", b"onum", b"onum", b"onum", b"onum", b"onum", b"ordn", b"ordn", b"ordn", b"ordn", b"ordn", b"pnum", b"pnum", b"pnum", b"pnum", b"pnum", b"sinf", b"sinf", b"sinf", b"sinf", b"sinf", b"subs", b"subs", b"subs", b"subs", b"subs", b"sups", b"sups", b"sups", b"sups", b"sups", b"tnum", b"tnum", b"tnum", b"tnum", b"tnum", b"zero", b"zero", b"zero", b"zero", b"zero", ] ); let lookups = features .records .iter() .map(|record| record.lookup_count) .collect::<Vec<_>>(); #[rustfmt::skip] assert!( lookups == vec![ 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ] ); }
function_block-full_function
[ { "content": "#![allow(dead_code, unused_macros)]\n\n\n\nuse std::fs::File;\n\nuse std::path::PathBuf;\n\n\n\nmacro_rules! ok(($result:expr) => ($result.unwrap()));\n\n\n\nmacro_rules! setup(\n\n ($fixture:ident) => (crate::common::setup(crate::common::Fixture::$fixture, None));\n\n ($fixture:ident, $tabl...
Rust
src/queue.rs
vext01/snare
39abfd107ff2b19ca4083b5e86f62f432436b7c0
use std::{ collections::{HashMap, VecDeque}, time::Instant, }; use crate::config::{QueueKind, RepoConfig}; pub(crate) struct QueueJob { pub repo_id: String, pub owner: String, pub repo: String, pub req_time: Instant, pub event_type: String, pub json_str: String, pub rconf: RepoConfig, } impl QueueJob { pub fn new( repo_id: String, owner: String, repo: String, req_time: Instant, event_type: String, json_str: String, rconf: RepoConfig, ) -> Self { QueueJob { repo_id, owner, repo, req_time, event_type, json_str, rconf, } } } pub(crate) struct Queue { q: HashMap<String, VecDeque<QueueJob>>, } impl Queue { pub fn new() -> Self { Queue { q: HashMap::new() } } pub fn is_empty(&self) -> bool { for v in self.q.values() { if !v.is_empty() { return false; } } true } pub fn push_back(&mut self, qj: QueueJob) { let mut entry = self.q.entry(qj.repo_id.clone()); match qj.rconf.queuekind { QueueKind::Evict => { entry = entry.and_modify(|v| v.clear()); } QueueKind::Parallel | QueueKind::Sequential => (), } entry.or_insert_with(VecDeque::new).push_back(qj); } pub fn push_front(&mut self, qj: QueueJob) { self.q .entry(qj.repo_id.clone()) .or_insert_with(VecDeque::new) .push_front(qj); } pub fn pop<F>(&mut self, running: F) -> Option<QueueJob> where F: Fn(&str) -> bool, { let mut earliest_time = None; let mut earliest_key = None; for (k, v) in self.q.iter() { if let Some(qj) = v.get(0) { if let Some(et) = earliest_time { if et > qj.req_time { continue; } } match qj.rconf.queuekind { QueueKind::Parallel => (), QueueKind::Evict | QueueKind::Sequential => { if running(&qj.repo_id) { continue; } } } earliest_time = Some(qj.req_time); earliest_key = Some(k.clone()); } } if let Some(k) = earliest_key { Some(self.q.get_mut(&k).unwrap().pop_front().unwrap()) } else { None } } }
use std::{ collections::{HashMap, VecDeque}, time::Instant, }; use crate::config::{QueueKind, RepoConfig}; pub(crate) struct QueueJob { pub repo_id: String, pub owner: String, pub repo: String, pub req_time: Instant, pub event_type: String, pub json_str: String, pub rconf: RepoConfig, } impl QueueJob { pub fn new( repo_id: String, owner: String, repo: String, req_time: Instant, event_type: String, json_str: String, rconf: RepoConfig, ) -> Self { QueueJob { repo_id, owner, repo, req_time, event_type, json_str, rconf, } } } pub(crate) struct Queue { q: HashMap<String, VecDeque<QueueJob>>, } impl Queue { pub fn new() -> Self { Queue { q: HashMap::new() } } pub fn is_empty(&self) -> bool { for v in self.q.values() { if !v.is_empty() { return false; } } true } pub fn push_back(&mut self, qj: QueueJob) { let mut entry = self.q.entry(qj.repo_id.clone()); match qj.rconf.queuekind { QueueKind::Evict => { entry = entry.and_modify(|v| v.clear());
epo_id) { continue; } } } earliest_time = Some(qj.req_time); earliest_key = Some(k.clone()); } } if let Some(k) = earliest_key { Some(self.q.get_mut(&k).unwrap().pop_front().unwrap()) } else { None } } }
} QueueKind::Parallel | QueueKind::Sequential => (), } entry.or_insert_with(VecDeque::new).push_back(qj); } pub fn push_front(&mut self, qj: QueueJob) { self.q .entry(qj.repo_id.clone()) .or_insert_with(VecDeque::new) .push_front(qj); } pub fn pop<F>(&mut self, running: F) -> Option<QueueJob> where F: Fn(&str) -> bool, { let mut earliest_time = None; let mut earliest_key = None; for (k, v) in self.q.iter() { if let Some(qj) = v.get(0) { if let Some(et) = earliest_time { if et > qj.req_time { continue; } } match qj.rconf.queuekind { QueueKind::Parallel => (), QueueKind::Evict | QueueKind::Sequential => { if running(&qj.r
random
[ { "content": "pub fn main() {\n\n let args: Vec<String> = env::args().collect();\n\n let matches = Options::new()\n\n .optmulti(\"c\", \"config\", \"Path to snare.conf.\", \"<conf-path>\")\n\n .optflag(\n\n \"d\",\n\n \"\",\n\n \"Don't detach from the termina...
Rust
retired/rusty/scalyc/src/scalyc/parser.copy.rs
rschleitzer/scaly
7537cdf44f7a63ad1a560975017ee1c897c73787
use scaly::containers::{Array, HashSet, Ref, String, Vector}; use scaly::io::Stream; use scaly::memory::Region; use scaly::Page; use scalyc::errors::ParserError; use scalyc::lexer::Lexer; use scalyc::lexer::Position; pub struct Parser { lexer: Ref<Lexer>, file_name: String, _keywords: Ref<HashSet<String>>, } impl Parser { pub fn new(_pr: &Region, _rp: *mut Page, file_name: String, stream: *mut Stream) -> Parser { let _r = Region::create(_pr); let keywords = HashSet::from_vector( &_r, _rp, Ref::new( _rp, Vector::from_raw_array( _rp, &[ String::from_string_slice(_rp, "using"), String::from_string_slice(_rp, "namespace"), String::from_string_slice(_rp, "typedef"), String::from_string_slice(_rp, "let"), String::from_string_slice(_rp, "mutable"), String::from_string_slice(_rp, "threadlocal"), String::from_string_slice(_rp, "var"), String::from_string_slice(_rp, "set"), String::from_string_slice(_rp, "class"), String::from_string_slice(_rp, "extends"), String::from_string_slice(_rp, "initializer"), String::from_string_slice(_rp, "allocator"), String::from_string_slice(_rp, "method"), String::from_string_slice(_rp, "function"), String::from_string_slice(_rp, "operator"), String::from_string_slice(_rp, "this"), String::from_string_slice(_rp, "new"), String::from_string_slice(_rp, "sizeof"), String::from_string_slice(_rp, "catch"), String::from_string_slice(_rp, "throws"), String::from_string_slice(_rp, "as"), String::from_string_slice(_rp, "is"), String::from_string_slice(_rp, "if"), String::from_string_slice(_rp, "else"), String::from_string_slice(_rp, "switch"), String::from_string_slice(_rp, "case"), String::from_string_slice(_rp, "default"), String::from_string_slice(_rp, "for"), String::from_string_slice(_rp, "in"), String::from_string_slice(_rp, "while"), String::from_string_slice(_rp, "do"), String::from_string_slice(_rp, "loop"), String::from_string_slice(_rp, "break"), String::from_string_slice(_rp, "continue"), String::from_string_slice(_rp, "return"), String::from_string_slice(_rp, "throw"), String::from_string_slice(_rp, "intrinsic"), String::from_string_slice(_rp, "define"), ], ), ), ); Parser { lexer: Lexer::new(&_r,_rp, stream), file_name: file_name, _keywords: keywords, } } pub fn parse_file( &mut self, _pr: &Region, _rp: *mut Page, _ep: *mut Page, ) -> Result<Ref<FileSyntax>, Ref<ParserError>> { let _r = Region::create(_pr); let start: Position = self.lexer.get_previous_position(); let statements = self.parse_statement_list(&_r, _rp); match statements { Some(_) => { if !self.is_at_end() { let error_pos = self.lexer.get_previous_position(); return Result::Err(Ref::new( _ep, ParserError { file_name: self.file_name, line: error_pos.line, column: error_pos.column, }, )); } } None => (), } let end: Position = self.lexer.get_position(); let ret: Ref<FileSyntax> = Ref::new( _rp, FileSyntax { start: start, end: end, }, ); Ok(ret) } pub fn parse_statement_list( &mut self, _pr: &Region, _rp: *mut Page, ) -> Option<Ref<Vector<Ref<StatementSyntax>>>> { let _r = Region::create(_pr); let mut ret: Option<Ref<Array<Ref<StatementSyntax>>>> = Option::None; loop { let node = self.parse_statement(&_r, _rp); match node { None => break, Some(node) => { match ret { None => ret = Some(Ref::new(_rp, Array::new())), Some(_) => (), }; ret.unwrap().add(node); } } } match ret { Some(ret) => Some(Ref::new(_rp, Vector::from_array(_rp, ret))), None => None, } } pub fn parse_statement( &mut self, _pr: &Region, _rp: *mut Page, ) -> Option<Ref<StatementSyntax>> { let _r = Region::create(_pr); let start: Position = self.lexer.get_previous_position(); let end: Position = self.lexer.get_position(); let ret: Ref<StatementSyntax> = Ref::new( _rp, StatementSyntax { start: start, end: end, }, ); Some(ret) } fn is_at_end(&self) -> bool { self.lexer.is_at_end() } fn _is_identifier(&self, id: String) -> bool { if self._keywords.contains(id) { false } else { true } } } #[derive(Copy, Clone)] pub struct FileSyntax { pub start: Position, pub end: Position, } #[derive(Copy, Clone)] pub struct StatementSyntax { pub start: Position, pub end: Position, }
use scaly::containers::{Array, HashSet, Ref, String, Vector}; use scaly::io::Stream; use scaly::memory::Region; use scaly::Page; use scalyc::errors::ParserError; use scalyc::lexer::Lexer; use scalyc::lexer::Position; pub struct Parser { lexer: Ref<Lexer>, file_name: String, _keywords: Ref<HashSet<String>>, } impl Parser { pub fn new(_pr: &Region, _rp: *mut Page, file_name: String, stream: *mut Stream) -> Parser { let _r = Region::create(_pr); let keywords = HashSet::from_vector( &_r, _rp, Ref::new( _rp, Vector::from_raw_array( _rp, &[ String::from_string_slice(_rp, "using"), String::from_string_slice(_rp, "namespace"), String::from_string_slice(_rp, "typedef"), String::from_string_slice(_rp, "let"), String::from_string_slice(_rp, "mutable"), String::from_string_slice(_rp, "threadlocal"), String::from_string_slice(_rp, "var"), String::from_string_slice(_rp, "set"), String::from_string_slice(_rp, "class"), String::from_string_slice(_rp, "extends"), String::from_string_slice(_rp, "initializer"), String::from_string_slice(_rp, "allocator"), String::f
Some(_) => (), }; ret.unwrap().add(node); } } } match ret { Some(ret) => Some(Ref::new(_rp, Vector::from_array(_rp, ret))), None => None, } } pub fn parse_statement( &mut self, _pr: &Region, _rp: *mut Page, ) -> Option<Ref<StatementSyntax>> { let _r = Region::create(_pr); let start: Position = self.lexer.get_previous_position(); let end: Position = self.lexer.get_position(); let ret: Ref<StatementSyntax> = Ref::new( _rp, StatementSyntax { start: start, end: end, }, ); Some(ret) } fn is_at_end(&self) -> bool { self.lexer.is_at_end() } fn _is_identifier(&self, id: String) -> bool { if self._keywords.contains(id) { false } else { true } } } #[derive(Copy, Clone)] pub struct FileSyntax { pub start: Position, pub end: Position, } #[derive(Copy, Clone)] pub struct StatementSyntax { pub start: Position, pub end: Position, }
rom_string_slice(_rp, "method"), String::from_string_slice(_rp, "function"), String::from_string_slice(_rp, "operator"), String::from_string_slice(_rp, "this"), String::from_string_slice(_rp, "new"), String::from_string_slice(_rp, "sizeof"), String::from_string_slice(_rp, "catch"), String::from_string_slice(_rp, "throws"), String::from_string_slice(_rp, "as"), String::from_string_slice(_rp, "is"), String::from_string_slice(_rp, "if"), String::from_string_slice(_rp, "else"), String::from_string_slice(_rp, "switch"), String::from_string_slice(_rp, "case"), String::from_string_slice(_rp, "default"), String::from_string_slice(_rp, "for"), String::from_string_slice(_rp, "in"), String::from_string_slice(_rp, "while"), String::from_string_slice(_rp, "do"), String::from_string_slice(_rp, "loop"), String::from_string_slice(_rp, "break"), String::from_string_slice(_rp, "continue"), String::from_string_slice(_rp, "return"), String::from_string_slice(_rp, "throw"), String::from_string_slice(_rp, "intrinsic"), String::from_string_slice(_rp, "define"), ], ), ), ); Parser { lexer: Lexer::new(&_r,_rp, stream), file_name: file_name, _keywords: keywords, } } pub fn parse_file( &mut self, _pr: &Region, _rp: *mut Page, _ep: *mut Page, ) -> Result<Ref<FileSyntax>, Ref<ParserError>> { let _r = Region::create(_pr); let start: Position = self.lexer.get_previous_position(); let statements = self.parse_statement_list(&_r, _rp); match statements { Some(_) => { if !self.is_at_end() { let error_pos = self.lexer.get_previous_position(); return Result::Err(Ref::new( _ep, ParserError { file_name: self.file_name, line: error_pos.line, column: error_pos.column, }, )); } } None => (), } let end: Position = self.lexer.get_position(); let ret: Ref<FileSyntax> = Ref::new( _rp, FileSyntax { start: start, end: end, }, ); Ok(ret) } pub fn parse_statement_list( &mut self, _pr: &Region, _rp: *mut Page, ) -> Option<Ref<Vector<Ref<StatementSyntax>>>> { let _r = Region::create(_pr); let mut ret: Option<Ref<Array<Ref<StatementSyntax>>>> = Option::None; loop { let node = self.parse_statement(&_r, _rp); match node { None => break, Some(node) => { match ret { None => ret = Some(Ref::new(_rp, Array::new())),
random
[ { "content": "fn _scalyc_main(_pr: &Region, arguments: Ref<Vector<String>>) {\n\n use scalyc::compiler::Compiler;\n\n let _r = Region::create(_pr);\n\n\n\n let compiler = Ref::new(_r.page, Compiler::new(_r.page, arguments));\n\n (*compiler).compile(&_r, _r.page, _r.page);\n\n}\n", "file_path": "...
Rust
src/solve/infer/instantiate.rs
gnzlbg/chalk
dc7dbad2244dd2c668fd49938d9d0ef77189bd23
use fallible::*; use fold::*; use std::fmt::Debug; use super::*; impl InferenceTable { fn instantiate<U, T>(&mut self, universes: U, arg: &T) -> T::Result where T: Fold + Debug, U: IntoIterator<Item = ParameterKind<UniverseIndex>>, { debug!("instantiate(arg={:?})", arg); let vars: Vec<_> = universes .into_iter() .map(|param_kind| self.parameter_kind_to_parameter(param_kind)) .collect(); debug!("instantiate: vars={:?}", vars); let mut instantiator = Instantiator { vars }; arg.fold_with(&mut instantiator, 0).expect("") } fn parameter_kind_to_parameter( &mut self, param_kind: ParameterKind<UniverseIndex>, ) -> Parameter { match param_kind { ParameterKind::Ty(ui) => ParameterKind::Ty(self.new_variable(ui).to_ty()), ParameterKind::Lifetime(ui) => { ParameterKind::Lifetime(self.new_variable(ui).to_lifetime()) } } } crate fn fresh_subst(&mut self, binders: &[ParameterKind<UniverseIndex>]) -> Substitution { Substitution { parameters: binders .iter() .map(|kind| { let param_infer_var = kind.map(|ui| self.new_variable(ui)); param_infer_var.to_parameter() }) .collect(), } } crate fn instantiate_canonical<T>(&mut self, bound: &Canonical<T>) -> T::Result where T: Fold + Debug, { self.instantiate(bound.binders.iter().cloned(), &bound.value) } crate fn instantiate_in<U, T>( &mut self, universe: UniverseIndex, binders: U, arg: &T, ) -> T::Result where T: Fold, U: IntoIterator<Item = ParameterKind<()>>, { self.instantiate(binders.into_iter().map(|pk| pk.map(|_| universe)), arg) } #[allow(non_camel_case_types)] crate fn instantiate_binders_existentially<T>( &mut self, arg: &impl BindersAndValue<Output = T>, ) -> T::Result where T: Fold, { let (binders, value) = arg.split(); let max_universe = self.max_universe; self.instantiate_in(max_universe, binders.iter().cloned(), value) } #[allow(non_camel_case_types)] crate fn instantiate_binders_universally<T>( &mut self, arg: &impl BindersAndValue<Output = T>, ) -> T::Result where T: Fold, { let (binders, value) = arg.split(); let parameters: Vec<_> = binders .iter() .map(|pk| { let new_universe = self.new_universe(); match *pk { ParameterKind::Lifetime(()) => { let lt = Lifetime::ForAll(new_universe); ParameterKind::Lifetime(lt) } ParameterKind::Ty(()) => ParameterKind::Ty(Ty::Apply(ApplicationTy { name: TypeName::ForAll(new_universe), parameters: vec![], })), } }) .collect(); Subst::apply(&parameters, value) } } crate trait BindersAndValue { type Output; fn split(&self) -> (&[ParameterKind<()>], &Self::Output); } impl<T> BindersAndValue for Binders<T> { type Output = T; fn split(&self) -> (&[ParameterKind<()>], &Self::Output) { (&self.binders, &self.value) } } impl<'a, T> BindersAndValue for (&'a Vec<ParameterKind<()>>, &'a T) { type Output = T; fn split(&self) -> (&[ParameterKind<()>], &Self::Output) { (&self.0, &self.1) } } struct Instantiator { vars: Vec<Parameter>, } impl DefaultTypeFolder for Instantiator {} impl ExistentialFolder for Instantiator { fn fold_free_existential_ty(&mut self, depth: usize, binders: usize) -> Fallible<Ty> { if depth < self.vars.len() { Ok(self.vars[depth].assert_ty_ref().up_shift(binders)) } else { Ok(Ty::Var(depth + binders - self.vars.len())) } } fn fold_free_existential_lifetime( &mut self, depth: usize, binders: usize, ) -> Fallible<Lifetime> { if depth < self.vars.len() { Ok(self.vars[depth].assert_lifetime_ref().up_shift(binders)) } else { Ok(Lifetime::Var(depth + binders - self.vars.len())) } } } impl IdentityUniversalFolder for Instantiator {}
use fallible::*; use fold::*; use std::fmt::Debug; use super::*; impl InferenceTable { fn instantiate<U, T>(&mut self, universes: U, arg: &T) -> T::Result where T: Fold + Debug, U: IntoIterator<Item = ParameterKind<UniverseIndex>>, { debug!("instantiate(arg={:?})", arg); let vars: Vec<_> = universes .into_iter() .map(|param_kind| self.parameter_kind_to_parameter(param_kind)) .collect(); debug!("instantiate: vars={:?}", vars); let mut instantiator = Instantiator { vars }; arg.fold_with(
lf) -> (&[ParameterKind<()>], &Self::Output) { (&self.0, &self.1) } } struct Instantiator { vars: Vec<Parameter>, } impl DefaultTypeFolder for Instantiator {} impl ExistentialFolder for Instantiator { fn fold_free_existential_ty(&mut self, depth: usize, binders: usize) -> Fallible<Ty> { if depth < self.vars.len() { Ok(self.vars[depth].assert_ty_ref().up_shift(binders)) } else { Ok(Ty::Var(depth + binders - self.vars.len())) } } fn fold_free_existential_lifetime( &mut self, depth: usize, binders: usize, ) -> Fallible<Lifetime> { if depth < self.vars.len() { Ok(self.vars[depth].assert_lifetime_ref().up_shift(binders)) } else { Ok(Lifetime::Var(depth + binders - self.vars.len())) } } } impl IdentityUniversalFolder for Instantiator {}
&mut instantiator, 0).expect("") } fn parameter_kind_to_parameter( &mut self, param_kind: ParameterKind<UniverseIndex>, ) -> Parameter { match param_kind { ParameterKind::Ty(ui) => ParameterKind::Ty(self.new_variable(ui).to_ty()), ParameterKind::Lifetime(ui) => { ParameterKind::Lifetime(self.new_variable(ui).to_lifetime()) } } } crate fn fresh_subst(&mut self, binders: &[ParameterKind<UniverseIndex>]) -> Substitution { Substitution { parameters: binders .iter() .map(|kind| { let param_infer_var = kind.map(|ui| self.new_variable(ui)); param_infer_var.to_parameter() }) .collect(), } } crate fn instantiate_canonical<T>(&mut self, bound: &Canonical<T>) -> T::Result where T: Fold + Debug, { self.instantiate(bound.binders.iter().cloned(), &bound.value) } crate fn instantiate_in<U, T>( &mut self, universe: UniverseIndex, binders: U, arg: &T, ) -> T::Result where T: Fold, U: IntoIterator<Item = ParameterKind<()>>, { self.instantiate(binders.into_iter().map(|pk| pk.map(|_| universe)), arg) } #[allow(non_camel_case_types)] crate fn instantiate_binders_existentially<T>( &mut self, arg: &impl BindersAndValue<Output = T>, ) -> T::Result where T: Fold, { let (binders, value) = arg.split(); let max_universe = self.max_universe; self.instantiate_in(max_universe, binders.iter().cloned(), value) } #[allow(non_camel_case_types)] crate fn instantiate_binders_universally<T>( &mut self, arg: &impl BindersAndValue<Output = T>, ) -> T::Result where T: Fold, { let (binders, value) = arg.split(); let parameters: Vec<_> = binders .iter() .map(|pk| { let new_universe = self.new_universe(); match *pk { ParameterKind::Lifetime(()) => { let lt = Lifetime::ForAll(new_universe); ParameterKind::Lifetime(lt) } ParameterKind::Ty(()) => ParameterKind::Ty(Ty::Apply(ApplicationTy { name: TypeName::ForAll(new_universe), parameters: vec![], })), } }) .collect(); Subst::apply(&parameters, value) } } crate trait BindersAndValue { type Output; fn split(&self) -> (&[ParameterKind<()>], &Self::Output); } impl<T> BindersAndValue for Binders<T> { type Output = T; fn split(&self) -> (&[ParameterKind<()>], &Self::Output) { (&self.binders, &self.value) } } impl<'a, T> BindersAndValue for (&'a Vec<ParameterKind<()>>, &'a T) { type Output = T; fn split(&se
random
[ { "content": "/// Applies the given folder to a value.\n\npub trait Fold: Debug {\n\n /// The type of value that will be produced once folding is done.\n\n /// Typically this is `Self`, unless `Self` contains borrowed\n\n /// values, in which case owned values are produced (for example,\n\n /// one ...
Rust
tests/control.rs
big-ab-games/badder-lang
4580103f70be866a8b151912433b4d369f7d4ba4
#![allow(clippy::cognitive_complexity)] use badder_lang::{controller::*, *}; use std::time::*; const NO_FLAG: IntFlag = 0; macro_rules! await_next_pause { ($controller:ident) => {{ $controller.refresh(); if $controller.paused() { $controller.unpause(); } let before = Instant::now(); let max_wait = Duration::from_secs(2); while !$controller.paused() && before.elapsed() < max_wait { $controller.refresh(); } let phase = $controller.current_phase(); assert!(phase.is_some(), "waited 2 seconds without pause"); phase.unwrap() }}; } const SRC: &str = " var loops # just count up in a loop while loops < 3 loops += 1 var plus1 = loops + 1"; #[test] fn controller_step_test() { let _ = env_logger::try_init(); let ast = Parser::parse_str(SRC).expect("parse"); let mut con = Controller::new_max_pause(); con.execute(ast); assert_eq!(await_next_pause!(con).src, SourceRef((2, 1), (2, 10))); assert_eq!(await_next_pause!(con).src, SourceRef((5, 1), (5, 16))); assert_eq!(await_next_pause!(con).src, SourceRef((5, 7), (5, 16))); assert_eq!(await_next_pause!(con).src, SourceRef((6, 5), (6, 15))); assert_eq!(await_next_pause!(con).src, SourceRef((6, 5), (6, 15))); assert_eq!(await_next_pause!(con).src, SourceRef((5, 7), (5, 16))); assert_eq!(await_next_pause!(con).src, SourceRef((6, 5), (6, 15))); assert_eq!(await_next_pause!(con).src, SourceRef((6, 5), (6, 15))); assert_eq!(await_next_pause!(con).src, SourceRef((5, 7), (5, 16))); assert_eq!(await_next_pause!(con).src, SourceRef((6, 5), (6, 15))); assert_eq!(await_next_pause!(con).src, SourceRef((6, 5), (6, 15))); assert_eq!(await_next_pause!(con).src, SourceRef((5, 7), (5, 16))); assert_eq!(await_next_pause!(con).src, SourceRef((8, 1), (8, 22))); assert_eq!(await_next_pause!(con).src, SourceRef((8, 13), (8, 22))); } macro_rules! assert_stack { ($stack:expr; $( $key:ident = ($index:expr, $int:expr) ),*) => {{ let stack = $stack; $( let id = Token::Id(stringify!($key).into()); let index = $index; if stack.len() <= index || !stack[index].contains_key(&id) { println!("Actual stack {:?}", stack); assert!(stack.len() > index, "Stack smaller than expected"); } if let Some(&FrameData::Value(val, ..)) = stack[index].get(&id) { assert_eq!(val, $int, "unexpected value for `{:?}`", id); } else { assert!(false, "No value for `{:?}` on stack", id); } )* }}; } const STACK_SRC: &str = " var a = 123 # 1 if a is 123 # 2,3 var b = 500 # 4 if b is 500 # 5,6 var c = 17 # 7 a = 30 # 8 a + 1 # 9"; #[test] fn phase_stack() { let _ = env_logger::try_init(); let ast = Parser::parse_str(STACK_SRC).expect("parse"); let mut con = Controller::new_max_pause(); con.execute(ast); await_next_pause!(con); assert_stack!(await_next_pause!(con).stack; a = (0, 123)); assert_stack!(await_next_pause!(con).stack; a = (0, 123)); assert_stack!(await_next_pause!(con).stack; a = (0, 123)); assert_stack!(await_next_pause!(con).stack; a = (0, 123), b = (1, 500)); assert_stack!(await_next_pause!(con).stack; a = (0, 123), b = (1, 500)); assert_stack!(await_next_pause!(con).stack; a = (0, 123), b = (1, 500)); assert_stack!(await_next_pause!(con).stack; a = (0, 123), b = (1, 500), c = (2, 17)); assert_stack!(await_next_pause!(con).stack; a = (0, 30)); con.unpause(); let before_result = Instant::now(); while con.result().is_none() && before_result.elapsed() < Duration::from_secs(2) { con.refresh(); } assert!(matches!(con.result(), Some(&Ok(31)))); } const EXTERNAL_FUN_SRC: &str = "\ # expect an external function `external_sum(nn)` var a = 12 fun plus_one(n) n + 1 var a123 = external_sum(123, a) a.plus_one().external_sum(a123) "; #[test] fn external_functions_num_args() { let _ = env_logger::try_init(); let start = Instant::now(); let ast = Parser::parse_str(EXTERNAL_FUN_SRC).expect("parse"); let mut con = Controller::new_no_pause(); con.add_external_function("external_sum(vv)"); con.execute(ast); loop { if let Some(call) = con.current_external_call() { assert_eq!(call.id, Token::Id("external_sum(vv)".into())); assert_eq!(call.args, vec![(123, NO_FLAG), (12, NO_FLAG)]); con.answer_external_call(Ok((135, NO_FLAG))); break; } assert!( start.elapsed() < Duration::from_secs(2), "Waited 2 seconds for expectation" ); con.refresh(); assert!(matches!(con.result(), None)); } loop { if let Some(call) = con.current_external_call() { assert_eq!(call.id, Token::Id("external_sum(vv)".into())); assert_eq!(call.args, vec![(13, NO_FLAG), (135, NO_FLAG)]); con.answer_external_call(Ok((-123, NO_FLAG))); break; } assert!( start.elapsed() < Duration::from_secs(2), "Waited 2 seconds for expectation" ); con.refresh(); assert!(matches!(con.result(), None)); } while con.result().is_none() && start.elapsed() < Duration::from_secs(2) { con.refresh(); } assert!(matches!(con.result(), Some(&Ok(-123)))); } const CALLED_FROM_SRC: &str = "\ var x fun do_a() if x < 2 # -> [7, 8], [7, 4, 7, 8] do_b() # -> [7, 8] fun do_b() x += 1 # -> [8], [4, 7, 8] do_a() # -> [8], [4, 7, 8] do_b() "; #[test] fn called_from_info() { let _ = env_logger::try_init(); let ast = Parser::parse_str(CALLED_FROM_SRC).expect("parse"); macro_rules! assert_called_from_line { ($phase:expr => $lines:expr) => {{ let phase = $phase; let simplified_actual: Vec<_> = phase.called_from.iter().map(|src| (src.0).0).collect(); let lines: Vec<usize> = $lines; if lines != simplified_actual { println!("Unexpected called_from from phase at {:?}", phase.src); assert_eq!(simplified_actual, lines) } }}; } let mut con = Controller::new_max_pause(); con.execute(ast); assert_called_from_line!(await_next_pause!(con) => vec![]); assert_called_from_line!(await_next_pause!(con) => vec![]); assert_called_from_line!(await_next_pause!(con) => vec![]); assert_called_from_line!(await_next_pause!(con) => vec![]); assert_called_from_line!(await_next_pause!(con) => vec![8]); assert_called_from_line!(await_next_pause!(con) => vec![8]); assert_called_from_line!(await_next_pause!(con) => vec![8]); assert_called_from_line!(await_next_pause!(con) => vec![7, 8]); assert_called_from_line!(await_next_pause!(con) => vec![7, 8]); assert_called_from_line!(await_next_pause!(con) => vec![7, 8]); assert_called_from_line!(await_next_pause!(con) => vec![4, 7, 8]); assert_called_from_line!(await_next_pause!(con) => vec![4, 7, 8]); assert_called_from_line!(await_next_pause!(con) => vec![4, 7, 8]); assert_called_from_line!(await_next_pause!(con) => vec![7, 4, 7, 8]); assert_called_from_line!(await_next_pause!(con) => vec![7, 4, 7, 8]); }
#![allow(clippy::cognitive_complexity)] use badder_lang::{controller::*, *}; use std::time::*; const NO_FLAG: IntFlag = 0; macro_rules! await_next_pause { ($controller:ident) => {{ $controller.refresh(); if $controller.paused() { $controller.unpause(); } let before = Instant::now(); let max_wait = Duration::from_secs(2); while !$controller.paused() && before.elapsed() < max_wait { $controller.refresh(); } let phase = $controller.current_phase(); assert!(phase.is_some(), "waited 2 seconds without pause"); phase.unwrap() }}; } const SRC: &str = " var loops # just count up in a loop while loops < 3 loops += 1 var plus1 = loops + 1"; #[test] fn controller_step_test() { let _ = env_logger::try_init(); let ast = Parser::parse_str(SRC).expect("parse"); let mut con = Controller::new_max_pause(); con.execute(ast); assert_eq!(await_next_pause!(con).src, SourceRef((2, 1), (2, 10))); assert_eq!(await_next_pause!(con).src, SourceRef((5, 1), (5, 16))); assert_eq!(await_next_pause!(con).src, SourceRef((5, 7), (5, 16))); assert_eq!(await_next_pause!(con).src, SourceRef((6, 5), (6, 15))); assert_eq!(await_next_pause!(con).src, SourceRef((6, 5), (6, 15)));
ack = $stack; $( let id = Token::Id(stringify!($key).into()); let index = $index; if stack.len() <= index || !stack[index].contains_key(&id) { println!("Actual stack {:?}", stack); assert!(stack.len() > index, "Stack smaller than expected"); } if let Some(&FrameData::Value(val, ..)) = stack[index].get(&id) { assert_eq!(val, $int, "unexpected value for `{:?}`", id); } else { assert!(false, "No value for `{:?}` on stack", id); } )* }}; } const STACK_SRC: &str = " var a = 123 # 1 if a is 123 # 2,3 var b = 500 # 4 if b is 500 # 5,6 var c = 17 # 7 a = 30 # 8 a + 1 # 9"; #[test] fn phase_stack() { let _ = env_logger::try_init(); let ast = Parser::parse_str(STACK_SRC).expect("parse"); let mut con = Controller::new_max_pause(); con.execute(ast); await_next_pause!(con); assert_stack!(await_next_pause!(con).stack; a = (0, 123)); assert_stack!(await_next_pause!(con).stack; a = (0, 123)); assert_stack!(await_next_pause!(con).stack; a = (0, 123)); assert_stack!(await_next_pause!(con).stack; a = (0, 123), b = (1, 500)); assert_stack!(await_next_pause!(con).stack; a = (0, 123), b = (1, 500)); assert_stack!(await_next_pause!(con).stack; a = (0, 123), b = (1, 500)); assert_stack!(await_next_pause!(con).stack; a = (0, 123), b = (1, 500), c = (2, 17)); assert_stack!(await_next_pause!(con).stack; a = (0, 30)); con.unpause(); let before_result = Instant::now(); while con.result().is_none() && before_result.elapsed() < Duration::from_secs(2) { con.refresh(); } assert!(matches!(con.result(), Some(&Ok(31)))); } const EXTERNAL_FUN_SRC: &str = "\ # expect an external function `external_sum(nn)` var a = 12 fun plus_one(n) n + 1 var a123 = external_sum(123, a) a.plus_one().external_sum(a123) "; #[test] fn external_functions_num_args() { let _ = env_logger::try_init(); let start = Instant::now(); let ast = Parser::parse_str(EXTERNAL_FUN_SRC).expect("parse"); let mut con = Controller::new_no_pause(); con.add_external_function("external_sum(vv)"); con.execute(ast); loop { if let Some(call) = con.current_external_call() { assert_eq!(call.id, Token::Id("external_sum(vv)".into())); assert_eq!(call.args, vec![(123, NO_FLAG), (12, NO_FLAG)]); con.answer_external_call(Ok((135, NO_FLAG))); break; } assert!( start.elapsed() < Duration::from_secs(2), "Waited 2 seconds for expectation" ); con.refresh(); assert!(matches!(con.result(), None)); } loop { if let Some(call) = con.current_external_call() { assert_eq!(call.id, Token::Id("external_sum(vv)".into())); assert_eq!(call.args, vec![(13, NO_FLAG), (135, NO_FLAG)]); con.answer_external_call(Ok((-123, NO_FLAG))); break; } assert!( start.elapsed() < Duration::from_secs(2), "Waited 2 seconds for expectation" ); con.refresh(); assert!(matches!(con.result(), None)); } while con.result().is_none() && start.elapsed() < Duration::from_secs(2) { con.refresh(); } assert!(matches!(con.result(), Some(&Ok(-123)))); } const CALLED_FROM_SRC: &str = "\ var x fun do_a() if x < 2 # -> [7, 8], [7, 4, 7, 8] do_b() # -> [7, 8] fun do_b() x += 1 # -> [8], [4, 7, 8] do_a() # -> [8], [4, 7, 8] do_b() "; #[test] fn called_from_info() { let _ = env_logger::try_init(); let ast = Parser::parse_str(CALLED_FROM_SRC).expect("parse"); macro_rules! assert_called_from_line { ($phase:expr => $lines:expr) => {{ let phase = $phase; let simplified_actual: Vec<_> = phase.called_from.iter().map(|src| (src.0).0).collect(); let lines: Vec<usize> = $lines; if lines != simplified_actual { println!("Unexpected called_from from phase at {:?}", phase.src); assert_eq!(simplified_actual, lines) } }}; } let mut con = Controller::new_max_pause(); con.execute(ast); assert_called_from_line!(await_next_pause!(con) => vec![]); assert_called_from_line!(await_next_pause!(con) => vec![]); assert_called_from_line!(await_next_pause!(con) => vec![]); assert_called_from_line!(await_next_pause!(con) => vec![]); assert_called_from_line!(await_next_pause!(con) => vec![8]); assert_called_from_line!(await_next_pause!(con) => vec![8]); assert_called_from_line!(await_next_pause!(con) => vec![8]); assert_called_from_line!(await_next_pause!(con) => vec![7, 8]); assert_called_from_line!(await_next_pause!(con) => vec![7, 8]); assert_called_from_line!(await_next_pause!(con) => vec![7, 8]); assert_called_from_line!(await_next_pause!(con) => vec![4, 7, 8]); assert_called_from_line!(await_next_pause!(con) => vec![4, 7, 8]); assert_called_from_line!(await_next_pause!(con) => vec![4, 7, 8]); assert_called_from_line!(await_next_pause!(con) => vec![7, 4, 7, 8]); assert_called_from_line!(await_next_pause!(con) => vec![7, 4, 7, 8]); }
assert_eq!(await_next_pause!(con).src, SourceRef((5, 7), (5, 16))); assert_eq!(await_next_pause!(con).src, SourceRef((6, 5), (6, 15))); assert_eq!(await_next_pause!(con).src, SourceRef((6, 5), (6, 15))); assert_eq!(await_next_pause!(con).src, SourceRef((5, 7), (5, 16))); assert_eq!(await_next_pause!(con).src, SourceRef((6, 5), (6, 15))); assert_eq!(await_next_pause!(con).src, SourceRef((6, 5), (6, 15))); assert_eq!(await_next_pause!(con).src, SourceRef((5, 7), (5, 16))); assert_eq!(await_next_pause!(con).src, SourceRef((8, 1), (8, 22))); assert_eq!(await_next_pause!(con).src, SourceRef((8, 13), (8, 22))); } macro_rules! assert_stack { ($stack:expr; $( $key:ident = ($index:expr, $int:expr) ),*) => {{ let st
random
[ { "content": "fn interested_in(ast: &Ast) -> bool {\n\n use crate::Ast::*;\n\n !matches!(\n\n *ast,\n\n LinePair(..)\n\n | Line(..)\n\n | Empty(..)\n\n | Num(..)\n\n | ReferSeq(..)\n\n | ReferSeqIndex(..)\n\n | Refer(..)\n\n ...
Rust
src/indexer/async.rs
jerry73204/rust-tffile
b0285d172c8a84413018e0cdf69437d164728a50
use super::{Position, RecordIndex, RecordIndexerConfig}; use crate::{ error::{Error, Result}, record::Record, utils, }; use async_std::{ fs::File, io::BufReader, path::{Path, PathBuf}, }; use futures::{ io::{AsyncRead, AsyncSeek, AsyncSeekExt as _}, stream, stream::{Stream, StreamExt as _, TryStreamExt as _}, }; use std::{borrow::Cow, future::Future, io::SeekFrom, sync::Arc}; impl RecordIndex { pub async fn load_async<T>(&self) -> Result<T> where T: Record, { let Self { ref path, offset, len, } = *self; let mut reader = BufReader::new(File::open(&**path).await?); let bytes = read_record_at(&mut reader, offset, len).await?; let record = T::from_bytes(bytes)?; Ok(record) } } pub async fn load_prefix_async<'a, P>( prefix: P, config: RecordIndexerConfig, ) -> Result<impl Stream<Item = Result<RecordIndex>>> where P: Into<Cow<'a, str>>, { let stream = load_prefix_futures(prefix, config) .await? .then(|fut| fut) .try_flatten(); Ok(stream) } pub async fn load_prefix_futures<'a, P>( prefix: P, config: RecordIndexerConfig, ) -> Result<impl Stream<Item = impl Future<Output = Result<impl Stream<Item = Result<RecordIndex>>>>>> where P: Into<Cow<'a, str>>, { let (dir, file_name_prefix) = utils::split_prefix(prefix); let dir = Path::new(&dir); let file_name_prefix = Arc::new(file_name_prefix); let mut paths: Vec<_> = dir .read_dir() .await? .map(|result| result.map_err(Error::from)) .try_filter_map(|entry| { let file_name_prefix = file_name_prefix.clone(); async move { if !entry.metadata().await?.is_file() { return Ok(None); } let file_name = PathBuf::from(entry.file_name()); let path = file_name .starts_with(&*file_name_prefix) .then(|| std::path::PathBuf::from(entry.path().into_os_string())); Ok(path) } }) .try_collect() .await?; paths.sort(); let stream = load_paths_futures(paths, config); Ok(stream) } pub fn load_paths_async<'a, P, I>( paths: I, config: RecordIndexerConfig, ) -> impl Stream<Item = Result<RecordIndex>> where I: IntoIterator<Item = P>, P: Into<Cow<'a, std::path::Path>>, { load_paths_futures(paths, config) .then(|fut| fut) .try_flatten() } pub fn load_paths_futures<'a, P, I>( paths: I, config: RecordIndexerConfig, ) -> impl Stream<Item = impl Future<Output = Result<impl Stream<Item = Result<RecordIndex>>>>> where I: IntoIterator<Item = P>, P: Into<Cow<'a, std::path::Path>>, { stream::iter(paths) .map(|path| path.into().into_owned()) .map(move |path| load_file_async(path, config.clone())) } pub async fn load_file_async<'a, P>( file: P, config: RecordIndexerConfig, ) -> Result<impl Stream<Item = Result<RecordIndex>>> where P: Into<Cow<'a, std::path::Path>>, { let file = file.into().into_owned(); let reader = BufReader::new(File::open(&file).await?); let file = Arc::new(std::path::PathBuf::from(file.into_os_string())); let stream = load_reader_async(reader, config).map(move |pos| { let Position { offset, len } = pos?; Ok(RecordIndex { path: file.clone(), offset, len, }) }); Ok(stream) } pub fn load_reader_async<R>( reader: R, config: RecordIndexerConfig, ) -> impl Stream<Item = Result<Position>> where R: AsyncRead + AsyncSeek + Unpin, { let RecordIndexerConfig { check_integrity } = config; stream::try_unfold(reader, move |mut reader| async move { let len = match crate::io::r#async::try_read_len(&mut reader, check_integrity).await? { Some(len) => len, None => return Ok(None), }; let offset = reader.seek(SeekFrom::Current(0)).await?; skip_or_check(&mut reader, len, check_integrity).await?; let pos = Position { offset, len }; Result::<_, Error>::Ok(Some((pos, reader))) }) } async fn read_record_at<R>(reader: &mut R, offset: u64, len: usize) -> Result<Vec<u8>> where R: AsyncRead + AsyncSeek + Unpin, { reader.seek(SeekFrom::Start(offset)).await?; let bytes = crate::io::r#async::try_read_record_data(reader, len, false).await?; Ok(bytes) } async fn skip_or_check<R>(reader: &mut R, len: usize, check_integrity: bool) -> Result<()> where R: AsyncRead + AsyncSeek + Unpin, { if check_integrity { crate::io::r#async::try_read_record_data(reader, len, check_integrity).await?; } else { reader.seek(SeekFrom::Current(len as i64)).await?; } Ok(()) }
use super::{Position, RecordIndex, RecordIndexerConfig}; use crate::{ error::{Error, Result}, record::Record, utils, }; use async_std::{ fs::File, io::BufReader, path::{Path, PathBuf}, }; use futures::{ io::{AsyncRead, AsyncSeek, AsyncSeekExt as _}, stream, stream::{Stream, StreamExt as _, TryStreamExt as _}, }; use std::{borrow::Cow, future::Future, io::SeekFrom, sync::Arc}; impl RecordIndex {
} pub async fn load_prefix_async<'a, P>( prefix: P, config: RecordIndexerConfig, ) -> Result<impl Stream<Item = Result<RecordIndex>>> where P: Into<Cow<'a, str>>, { let stream = load_prefix_futures(prefix, config) .await? .then(|fut| fut) .try_flatten(); Ok(stream) } pub async fn load_prefix_futures<'a, P>( prefix: P, config: RecordIndexerConfig, ) -> Result<impl Stream<Item = impl Future<Output = Result<impl Stream<Item = Result<RecordIndex>>>>>> where P: Into<Cow<'a, str>>, { let (dir, file_name_prefix) = utils::split_prefix(prefix); let dir = Path::new(&dir); let file_name_prefix = Arc::new(file_name_prefix); let mut paths: Vec<_> = dir .read_dir() .await? .map(|result| result.map_err(Error::from)) .try_filter_map(|entry| { let file_name_prefix = file_name_prefix.clone(); async move { if !entry.metadata().await?.is_file() { return Ok(None); } let file_name = PathBuf::from(entry.file_name()); let path = file_name .starts_with(&*file_name_prefix) .then(|| std::path::PathBuf::from(entry.path().into_os_string())); Ok(path) } }) .try_collect() .await?; paths.sort(); let stream = load_paths_futures(paths, config); Ok(stream) } pub fn load_paths_async<'a, P, I>( paths: I, config: RecordIndexerConfig, ) -> impl Stream<Item = Result<RecordIndex>> where I: IntoIterator<Item = P>, P: Into<Cow<'a, std::path::Path>>, { load_paths_futures(paths, config) .then(|fut| fut) .try_flatten() } pub fn load_paths_futures<'a, P, I>( paths: I, config: RecordIndexerConfig, ) -> impl Stream<Item = impl Future<Output = Result<impl Stream<Item = Result<RecordIndex>>>>> where I: IntoIterator<Item = P>, P: Into<Cow<'a, std::path::Path>>, { stream::iter(paths) .map(|path| path.into().into_owned()) .map(move |path| load_file_async(path, config.clone())) } pub async fn load_file_async<'a, P>( file: P, config: RecordIndexerConfig, ) -> Result<impl Stream<Item = Result<RecordIndex>>> where P: Into<Cow<'a, std::path::Path>>, { let file = file.into().into_owned(); let reader = BufReader::new(File::open(&file).await?); let file = Arc::new(std::path::PathBuf::from(file.into_os_string())); let stream = load_reader_async(reader, config).map(move |pos| { let Position { offset, len } = pos?; Ok(RecordIndex { path: file.clone(), offset, len, }) }); Ok(stream) } pub fn load_reader_async<R>( reader: R, config: RecordIndexerConfig, ) -> impl Stream<Item = Result<Position>> where R: AsyncRead + AsyncSeek + Unpin, { let RecordIndexerConfig { check_integrity } = config; stream::try_unfold(reader, move |mut reader| async move { let len = match crate::io::r#async::try_read_len(&mut reader, check_integrity).await? { Some(len) => len, None => return Ok(None), }; let offset = reader.seek(SeekFrom::Current(0)).await?; skip_or_check(&mut reader, len, check_integrity).await?; let pos = Position { offset, len }; Result::<_, Error>::Ok(Some((pos, reader))) }) } async fn read_record_at<R>(reader: &mut R, offset: u64, len: usize) -> Result<Vec<u8>> where R: AsyncRead + AsyncSeek + Unpin, { reader.seek(SeekFrom::Start(offset)).await?; let bytes = crate::io::r#async::try_read_record_data(reader, len, false).await?; Ok(bytes) } async fn skip_or_check<R>(reader: &mut R, len: usize, check_integrity: bool) -> Result<()> where R: AsyncRead + AsyncSeek + Unpin, { if check_integrity { crate::io::r#async::try_read_record_data(reader, len, check_integrity).await?; } else { reader.seek(SeekFrom::Current(len as i64)).await?; } Ok(()) }
pub async fn load_async<T>(&self) -> Result<T> where T: Record, { let Self { ref path, offset, len, } = *self; let mut reader = BufReader::new(File::open(&**path).await?); let bytes = read_record_at(&mut reader, offset, len).await?; let record = T::from_bytes(bytes)?; Ok(record) }
function_block-full_function
[ { "content": "pub fn split_prefix<'a>(prefix: impl Into<Cow<'a, str>>) -> (PathBuf, OsString) {\n\n let prefix = prefix.into();\n\n if prefix.ends_with(MAIN_SEPARATOR) {\n\n let dir = PathBuf::from(prefix.into_owned());\n\n (dir, OsString::from(\"\"))\n\n } else {\n\n let prefix = ...
Rust
src/population.rs
Phlosioneer/neat-learning
60fb7d37b8b7678b17b499313a95a664b19e504c
use genome::Genome; use rand::Rng; use std::collections::HashMap; use Environment; pub struct Counter { innovation: u64, node: usize, cached_connections: HashMap<(usize, usize), u64>, cached_splits: HashMap<(usize, usize), (u64, usize)>, } impl Counter { pub fn new() -> Counter { Counter { innovation: 0, node: 0, cached_connections: HashMap::new(), cached_splits: HashMap::new(), } } #[cfg(test)] pub fn from_id(start: usize) -> Counter { Counter { innovation: start as u64, node: start, cached_connections: HashMap::new(), cached_splits: HashMap::new(), } } fn next_innovation(&mut self) -> u64 { let temp = self.innovation; self.innovation += 1; temp } fn next_node(&mut self) -> usize { let temp = self.node; self.node += 1; temp } pub fn new_connection(&mut self, input_node: usize, output_node: usize) -> u64 { { let maybe_ret = self.cached_connections.get(&(input_node, output_node)); if let Some(&innovation) = maybe_ret { return innovation; } } let innovation = self.next_innovation(); self.cached_connections .insert((input_node, output_node), innovation); innovation } pub fn new_split(&mut self, input_node: usize, output_node: usize) -> (u64, usize) { { let maybe_ret = self.cached_splits.get(&(input_node, output_node)); if let Some(&(innovation, node)) = maybe_ret { return (innovation, node); } } let innovation = self.next_innovation(); let node = self.next_node(); self.cached_splits .insert((input_node, output_node), (innovation, node)); (innovation, node) } pub fn clear_innovations(&mut self) { self.cached_connections.clear(); self.cached_splits.clear(); } } pub struct Population<R: Rng> { members: Vec<Genome>, max_size: usize, rng: R, counter: Counter, } impl<R: Rng> Population<R> { pub fn new(max_size: usize, rng: R) -> Population<R> { Population { members: Vec::new(), max_size, rng, counter: Counter::new(), } } pub fn initialize<E: Environment>(&mut self, env: &mut E) { self.members.clear(); let input_count = env.input_count(); let output_count = env.output_count(); if input_count == 0 { panic!("0 inputs to genome! Check your Environment impl."); } if output_count == 0 { panic!("0 outputs from genome! Check your Environment impl."); } self.counter.clear_innovations(); for _ in 0..self.max_size { let member = E::random_genome(&mut self.rng, &mut self.counter, input_count, output_count); self.members.push(member); } self.counter.clear_innovations(); } pub fn len(&self) -> usize { self.members.len() } pub fn max_len(&self) -> usize { self.max_size } /*pub fn evolve_once(&mut self, env: &mut Environment) -> Genome { }*/ } #[cfg(test)] mod test { use super::*; use util::test_util; use NetworkEnv; #[test] pub fn test_initialize_makes_max_size() { let rng = test_util::new_rng(None); let mut pop = Population::new(150, rng); pop.initialize(&mut NetworkEnv); assert_eq!(pop.len(), 150); } }
use genome::Genome; use rand::Rng; use std::collections::HashMap; use Environment; pub struct Counter { innovation: u64, node: usize, cached_connections: HashMap<(usize, usize), u64>, cached_splits: HashMap<(usize, usize), (u64, usize)>, } impl Counter { pub fn new() -> Counter { Counter { innovation: 0, node: 0, cached_connections: HashMap::new(), cached_splits: HashMap::new(), } } #[cfg(test)] pub fn from_id(start: usize) -> Counter { Counter { innovation: start as u64,
node); } } let innovation = self.next_innovation(); let node = self.next_node(); self.cached_splits .insert((input_node, output_node), (innovation, node)); (innovation, node) } pub fn clear_innovations(&mut self) { self.cached_connections.clear(); self.cached_splits.clear(); } } pub struct Population<R: Rng> { members: Vec<Genome>, max_size: usize, rng: R, counter: Counter, } impl<R: Rng> Population<R> { pub fn new(max_size: usize, rng: R) -> Population<R> { Population { members: Vec::new(), max_size, rng, counter: Counter::new(), } } pub fn initialize<E: Environment>(&mut self, env: &mut E) { self.members.clear(); let input_count = env.input_count(); let output_count = env.output_count(); if input_count == 0 { panic!("0 inputs to genome! Check your Environment impl."); } if output_count == 0 { panic!("0 outputs from genome! Check your Environment impl."); } self.counter.clear_innovations(); for _ in 0..self.max_size { let member = E::random_genome(&mut self.rng, &mut self.counter, input_count, output_count); self.members.push(member); } self.counter.clear_innovations(); } pub fn len(&self) -> usize { self.members.len() } pub fn max_len(&self) -> usize { self.max_size } /*pub fn evolve_once(&mut self, env: &mut Environment) -> Genome { }*/ } #[cfg(test)] mod test { use super::*; use util::test_util; use NetworkEnv; #[test] pub fn test_initialize_makes_max_size() { let rng = test_util::new_rng(None); let mut pop = Population::new(150, rng); pop.initialize(&mut NetworkEnv); assert_eq!(pop.len(), 150); } }
node: start, cached_connections: HashMap::new(), cached_splits: HashMap::new(), } } fn next_innovation(&mut self) -> u64 { let temp = self.innovation; self.innovation += 1; temp } fn next_node(&mut self) -> usize { let temp = self.node; self.node += 1; temp } pub fn new_connection(&mut self, input_node: usize, output_node: usize) -> u64 { { let maybe_ret = self.cached_connections.get(&(input_node, output_node)); if let Some(&innovation) = maybe_ret { return innovation; } } let innovation = self.next_innovation(); self.cached_connections .insert((input_node, output_node), innovation); innovation } pub fn new_split(&mut self, input_node: usize, output_node: usize) -> (u64, usize) { { let maybe_ret = self.cached_splits.get(&(input_node, output_node)); if let Some(&(innovation, node)) = maybe_ret { return (innovation,
random
[ { "content": "pub trait Environment {\n\n fn fitness_type() -> FitnessType;\n\n\n\n fn input_count(&self) -> usize;\n\n fn output_count(&self) -> usize;\n\n\n\n fn calc_fitness(&self, organism: &Organism) -> f64;\n\n fn random_genome<R: Rng>(\n\n rng: &mut R,\n\n counter: &mut Count...
Rust
src/serialize_b2_body.rs
yangfengzzz/box2d-rs
0f41603d786545a8dee08d09f743a51e8de78bea
use serde::de::{self, Deserializer, MapAccess, SeqAccess, Visitor}; use serde::{ ser::{SerializeStruct}, Deserialize, Serialize, Serializer, }; use serde::de::DeserializeSeed; use std::fmt; use std::rc::{Rc}; use crate::b2_body::*; use crate::b2_settings::*; use crate::b2_world::*; use crate::serialize_b2_fixture::*; use strum::VariantNames; use strum_macros::EnumVariantNames; trait B2bodyToDef<D: UserDataType> { fn get_def(&self) -> B2bodyDef<D>; } impl<D: UserDataType> B2bodyToDef<D> for B2body<D> { fn get_def(&self) -> B2bodyDef<D> { return B2bodyDef { body_type: self.m_type, position: self.m_xf.p, angle: self.m_sweep.a, linear_velocity: self.m_linear_velocity, angular_velocity: self.m_angular_velocity, linear_damping: self.m_linear_damping, angular_damping: self.m_angular_damping, allow_sleep: self.m_flags.contains(BodyFlags::E_AUTO_SLEEP_FLAG), awake: self.m_flags.contains(BodyFlags::E_AWAKE_FLAG), fixed_rotation: self.m_flags.contains(BodyFlags::E_FIXED_ROTATION_FLAG), bullet: self.m_flags.contains(BodyFlags::E_BULLET_FLAG), enabled: self.m_flags.contains(BodyFlags::E_ENABLED_FLAG), gravity_scale: self.m_gravity_scale, user_data: self.m_user_data.clone(), }; } } impl<D: UserDataType> Serialize for B2body<D> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut state = serializer.serialize_struct("B2body", 2)?; let definition = self.get_def(); state.serialize_field("m_definition", &definition)?; state.serialize_field("m_fixture_list", &self.m_fixture_list)?; state.end() } } #[derive(Clone)] pub(crate) struct B2bodyDefinitionVisitorContext<D: UserDataType> { pub(crate) m_world: B2worldWeakPtr<D>, } impl<'de, U: UserDataType> DeserializeSeed<'de> for B2bodyDefinitionVisitorContext<U> { type Value = (); fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { #[derive(Deserialize)] #[serde(field_identifier, rename_all = "lowercase")] #[derive(EnumVariantNames)] enum Field { m_definition, m_fixture_list, }; struct B2bodyDefinitionVisitor<D: UserDataType>(B2bodyDefinitionVisitorContext<D>); impl<'de, U: UserDataType> Visitor<'de> for B2bodyDefinitionVisitor<U> { type Value = (); fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("struct B2fixture") } fn visit_seq<V>(self, mut seq: V) -> Result<Self::Value, V::Error> where V: SeqAccess<'de>, { let world = self.0.m_world.upgrade().unwrap(); let def: B2bodyDef<U> = seq .next_element()? .ok_or_else(|| de::Error::invalid_length(0, &self))?; let body = Some(B2world::create_body(world.clone(), &def)); seq.next_element_seed(B2fixtureListVisitorContext { body: Rc::downgrade(&body.clone().unwrap()), })? .ok_or_else(|| de::Error::invalid_length(0, &self))?; Ok(()) } fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error> where V: MapAccess<'de>, { let mut body = None; let world = self.0.m_world.upgrade().unwrap(); while let Some(key) = map.next_key()? { match key { Field::m_definition => { let def: B2bodyDef<U> = map.next_value()?; body = Some(B2world::create_body(world.clone(), &def)); } Field::m_fixture_list => { map.next_value_seed(B2fixtureListVisitorContext { body: Rc::downgrade(&body.clone().unwrap()), })?; } } } Ok(()) } } deserializer.deserialize_struct("B2body", Field::VARIANTS, B2bodyDefinitionVisitor(self)) } } pub(crate) struct B2bodyVisitorContext<D: UserDataType> { pub(crate) m_world: B2worldWeakPtr<D>, } impl<'de, U: UserDataType> DeserializeSeed<'de> for B2bodyVisitorContext<U> { type Value = (); fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { struct B2bodyVisitor<D: UserDataType>(B2bodyVisitorContext<D>); impl<'de, U: UserDataType> Visitor<'de> for B2bodyVisitor<U> { type Value = (); fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("struct B2fixture") } fn visit_seq<V>(self, mut seq: V) -> Result<Self::Value, V::Error> where V: SeqAccess<'de>, { let context = B2bodyDefinitionVisitorContext { m_world: self.0.m_world.clone(), }; while let Some(elem) = seq.next_element_seed(context.clone())? {} Ok(()) } } deserializer.deserialize_seq(B2bodyVisitor(self)) } }
use serde::de::{self, Deserializer, MapAccess, SeqAccess, Visitor}; use serde::{ ser::{SerializeStruct}, Deserialize, Serialize, Serializer, }; use serde::de::DeserializeSeed; use std::fmt; use std::rc::{Rc}; use crate::b2_body::*; use crate::b2_settings::*; use crate::b2_world::*; use crate::serialize_b2_fixture::*; use strum::VariantNames; use strum_macros::EnumVariantNames; trait B2bodyToDef<D: UserDataType> { fn get_def(&self) -> B2bodyDef<D>; } impl<D: UserDataType> B2bodyToDef<D> for B2body<D> { fn get_def(&self) -> B2bodyDef<D> { return B2bodyDef { body_type: self.m_type, position: self.m_xf.p, angle: self.m_sweep.a, linear_velocity: self.m_linear_velocity, angular_velocity: self.m_angular_velocity, linear_damping: self.m_linear_damping, angular_damping: self.m_angular_damping, allow_sleep: self.m_flags.contains(BodyFlags::E_AUTO_SLEEP_FLAG), awake: self.m_flags.contains(BodyFlags::E_AWAKE_FLAG), fixed_rotation: self.m_flags.contains(BodyFlags::E_FIXED_ROTATION_FLAG), bullet: self.m_flags.contains(BodyFlags::E_BULLET_FLAG), enabled: self.m_flags.contains(BodyFlags::E_ENABLED_FLAG), gravity_scale: self.m_gravity_scale, user_data: self.m_user_data.clone(), }; } } impl<D: UserDataType> Serialize for B2body<D> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut state = serializer.serialize_struct("B2body", 2)?; let definition = self.get_def(); state.serialize_field("m_definition", &definition)?; state.serialize_field("m_fixture_list", &self.m_fixture_list)?; state.end() } } #[derive(Clone)] pub(crate) struct B2bodyDefinitionVisitorContext<D: UserDataType> { pub(crate) m_world: B2worldWeakPtr<D>, } impl<'de, U: UserDataType> DeserializeSeed<'de> for B2bodyDefinitionVisitorContext<U> { type Value = (); fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { #[derive(Deserialize)] #[serde(field_identifier, rename_all = "lowercase")] #[derive(EnumVariantNames)] enum Field { m_definition, m_fixture_list, }; struct B2bodyDefinitionVisitor<D: UserDataType>(B2bodyDefinitionVisitorContext<D>); impl<'de, U: UserDataType> Visitor<'de> for B2bodyDefinitionVisitor<U> { type Value = (); fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("struct B2fixture") } fn visit_seq<V>(self, mut seq: V) -> Result<Self::Value, V::Error> where V: SeqAccess<'de>, { let world = self.0.m_world.upgrade().unwrap(); let def: B2bodyDef<U> = seq .next_element()? .ok_or_else(|| de::Error::invalid_length(0, &self))?; let body = Some(B2world::create_body(world.clone(), &def)); seq.next_element_seed(B2fixtureListVisitorContext { body: Rc::downgrade(&body.clone().unwrap()), })? .
} pub(crate) struct B2bodyVisitorContext<D: UserDataType> { pub(crate) m_world: B2worldWeakPtr<D>, } impl<'de, U: UserDataType> DeserializeSeed<'de> for B2bodyVisitorContext<U> { type Value = (); fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { struct B2bodyVisitor<D: UserDataType>(B2bodyVisitorContext<D>); impl<'de, U: UserDataType> Visitor<'de> for B2bodyVisitor<U> { type Value = (); fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("struct B2fixture") } fn visit_seq<V>(self, mut seq: V) -> Result<Self::Value, V::Error> where V: SeqAccess<'de>, { let context = B2bodyDefinitionVisitorContext { m_world: self.0.m_world.clone(), }; while let Some(elem) = seq.next_element_seed(context.clone())? {} Ok(()) } } deserializer.deserialize_seq(B2bodyVisitor(self)) } }
ok_or_else(|| de::Error::invalid_length(0, &self))?; Ok(()) } fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error> where V: MapAccess<'de>, { let mut body = None; let world = self.0.m_world.upgrade().unwrap(); while let Some(key) = map.next_key()? { match key { Field::m_definition => { let def: B2bodyDef<U> = map.next_value()?; body = Some(B2world::create_body(world.clone(), &def)); } Field::m_fixture_list => { map.next_value_seed(B2fixtureListVisitorContext { body: Rc::downgrade(&body.clone().unwrap()), })?; } } } Ok(()) } } deserializer.deserialize_struct("B2body", Field::VARIANTS, B2bodyDefinitionVisitor(self)) }
function_block-function_prefix_line
[ { "content": "pub fn synchronize_fixtures_by_world<D: UserDataType>(self_: &mut B2body<D>, world: &B2world<D>) {\n\n\tsynchronize_fixtures_internal(self_, world);\n\n}\n\n\n", "file_path": "src/private/dynamics/b2_body.rs", "rank": 0, "score": 291282.27457034343 }, { "content": "pub fn set_t...
Rust
rs/crypto/internal/crypto_lib/basic_sig/ed25519/src/types/conversions.rs
3cL1p5e7/ic
2b6011291d900454cedcf86ec41c8c1994fdf7d9
use super::*; use ic_crypto_secrets_containers::SecretArray; use ic_types::crypto::{AlgorithmId, CryptoError}; use std::convert::TryFrom; pub mod protobuf; #[cfg(test)] mod tests; impl From<SecretKeyBytes> for String { fn from(val: SecretKeyBytes) -> Self { base64::encode(val.0.expose_secret()) } } impl TryFrom<&str> for SecretKeyBytes { type Error = CryptoError; fn try_from(key: &str) -> Result<Self, CryptoError> { let mut key = base64::decode(key).map_err(|e| CryptoError::MalformedSecretKey { algorithm: AlgorithmId::Ed25519, internal_error: format!("Key is not a valid base64 encoded string: {}", e), })?; if key.len() != SecretKeyBytes::SIZE { return Err(CryptoError::MalformedSecretKey { algorithm: AlgorithmId::Ed25519, internal_error: "Key length is incorrect".to_string(), }); } let mut buffer = [0u8; SecretKeyBytes::SIZE]; buffer.copy_from_slice(&key); key.zeroize(); let ret = SecretKeyBytes(SecretArray::new_and_zeroize_argument(&mut buffer)); Ok(ret) } } impl TryFrom<&String> for SecretKeyBytes { type Error = CryptoError; fn try_from(signature: &String) -> Result<Self, CryptoError> { Self::try_from(signature as &str) } } impl From<PublicKeyBytes> for String { fn from(val: PublicKeyBytes) -> Self { base64::encode(&val.0[..]) } } impl TryFrom<&Vec<u8>> for PublicKeyBytes { type Error = CryptoError; fn try_from(key: &Vec<u8>) -> Result<Self, CryptoError> { if key.len() != PublicKeyBytes::SIZE { return Err(CryptoError::MalformedPublicKey { algorithm: AlgorithmId::Ed25519, key_bytes: Some(key.to_vec()), internal_error: format!( "Incorrect key length: expected {}, got {}.", PublicKeyBytes::SIZE, key.len() ), }); } let mut buffer = [0u8; PublicKeyBytes::SIZE]; buffer.copy_from_slice(key); Ok(PublicKeyBytes(buffer)) } } impl TryFrom<&str> for PublicKeyBytes { type Error = CryptoError; fn try_from(key: &str) -> Result<Self, CryptoError> { let key = base64::decode(key).map_err(|e| CryptoError::MalformedPublicKey { algorithm: AlgorithmId::Ed25519, key_bytes: None, internal_error: format!("Key {} is not a valid base64 encoded string: {}", key, e), })?; PublicKeyBytes::try_from(&key) } } impl TryFrom<&String> for PublicKeyBytes { type Error = CryptoError; fn try_from(signature: &String) -> Result<Self, CryptoError> { Self::try_from(signature as &str) } } impl From<SignatureBytes> for String { fn from(val: SignatureBytes) -> Self { base64::encode(&val.0[..]) } } impl TryFrom<&Vec<u8>> for SignatureBytes { type Error = CryptoError; fn try_from(signature_bytes: &Vec<u8>) -> Result<Self, CryptoError> { if signature_bytes.len() != SignatureBytes::SIZE { return Err(CryptoError::MalformedSignature { algorithm: AlgorithmId::Ed25519, sig_bytes: signature_bytes.clone(), internal_error: format!( "Incorrect signature length: expected {}, got {}.", SignatureBytes::SIZE, signature_bytes.len() ), }); } let mut buffer = [0u8; SignatureBytes::SIZE]; buffer.copy_from_slice(signature_bytes); Ok(SignatureBytes(buffer)) } } impl TryFrom<&str> for SignatureBytes { type Error = CryptoError; fn try_from(signature: &str) -> Result<Self, CryptoError> { let signature = base64::decode(signature).map_err(|e| CryptoError::MalformedSignature { algorithm: AlgorithmId::Ed25519, sig_bytes: Vec::new(), internal_error: format!( "Signature {} is not a valid base64 encoded string: {}", signature, e ), })?; if signature.len() != SignatureBytes::SIZE { return Err(CryptoError::MalformedSignature { algorithm: AlgorithmId::Ed25519, sig_bytes: signature, internal_error: "Signature length is incorrect".to_string(), }); } let mut buffer = [0u8; SignatureBytes::SIZE]; buffer.copy_from_slice(&signature); Ok(Self(buffer)) } } impl TryFrom<&String> for SignatureBytes { type Error = CryptoError; fn try_from(signature: &String) -> Result<Self, CryptoError> { Self::try_from(signature as &str) } }
use super::*; use ic_crypto_secrets_containers::SecretArray; use ic_types::crypto::{AlgorithmId, CryptoError}; use std::convert::TryFrom; pub mod protobuf; #[cfg(test)] mod tests; impl From<SecretKeyBytes> for String { fn from(val: SecretKeyBytes) -> Self { base64::encode(val.0.expose_secret()) } } impl TryFrom<&str> for SecretKeyBytes { type Error = CryptoError; fn try_from(key: &str) -> Result<Self, CryptoError> { let mut key = base64::decode(key).map_err(|e| CryptoError::MalformedSecretKey { algorithm: AlgorithmId::Ed25519, internal_error: format!("Key is not a valid base64 encoded string: {}", e), })?; if key.len() != SecretKeyBytes::SIZE { return Err(CryptoError::MalformedSecretKey { algorithm: AlgorithmId::Ed25519, internal_error: "Key length is incorrect".to_string(), }); } let mut buffer = [0u8; SecretKeyBytes::SIZE]; buffer.copy_from_slice(&key); key.zeroize(); let ret = SecretKeyBytes(SecretArray::new_and_zeroize_argument(&mut buffer)); Ok(ret) } } impl TryFrom<&String> for SecretKeyBytes { type Error = CryptoError; fn try_from(signature: &String) -> Result<Self, CryptoError> { Self::try_from(signature as &str) } } impl From<PublicKeyBytes> for String { fn from(val: PublicKeyBytes) -> Self { base64::encode(&val.0[..]) } } impl TryFrom<&Vec<u8>> for PublicKeyBytes { type Error = CryptoError; fn try_from(key: &Vec<u8>) -> Result<Self, CryptoError> { if key.len() != PublicKeyBytes::SIZE { return Err(CryptoError::MalformedPublicKey { algorithm: AlgorithmId::Ed25519, key_bytes: Some(key.to_vec()), internal_error: format!( "Incorrect key length: expected {}, got {}.", PublicKeyBytes::SIZE, key.len() ), }); } let mut buffer = [0u8; PublicKeyBytes::SIZE]; buffer.copy_from_slice(key); Ok(PublicKeyBytes(buffer)) } } impl TryFrom<&str> for PublicKeyBytes { type Error = CryptoError; fn try_from(key: &str) -> Result<Self, CryptoError> { let key = base64::decode(key).map_err(|e| CryptoError::MalformedPublicKey { algorithm: AlgorithmId::Ed25519, key_bytes: None, internal_error: format!("Key {} is not a valid base64 encoded string: {}", key, e), })?; PublicKeyBytes::try_from(&key) } } impl TryFrom<&String> for PublicKeyBytes { type Error = CryptoError; fn try_from(signature: &String) -> Result<Self, CryptoError> { Self::try_from(signature as &str) } } impl From<SignatureBytes> for String { fn from(val: SignatureBytes) -> Self { base64::encode(&val.0[..]) } } impl TryFrom<&Vec<u8>> for SignatureBytes { type Error = CryptoError; fn try_from(signature_bytes: &Vec<u8>) -> Result<Self, CryptoError> { if signature_bytes.len() != SignatureBytes::SIZE { return
; } let mut buffer = [0u8; SignatureBytes::SIZE]; buffer.copy_from_slice(signature_bytes); Ok(SignatureBytes(buffer)) } } impl TryFrom<&str> for SignatureBytes { type Error = CryptoError; fn try_from(signature: &str) -> Result<Self, CryptoError> { let signature = base64::decode(signature).map_err(|e| CryptoError::MalformedSignature { algorithm: AlgorithmId::Ed25519, sig_bytes: Vec::new(), internal_error: format!( "Signature {} is not a valid base64 encoded string: {}", signature, e ), })?; if signature.len() != SignatureBytes::SIZE { return Err(CryptoError::MalformedSignature { algorithm: AlgorithmId::Ed25519, sig_bytes: signature, internal_error: "Signature length is incorrect".to_string(), }); } let mut buffer = [0u8; SignatureBytes::SIZE]; buffer.copy_from_slice(&signature); Ok(Self(buffer)) } } impl TryFrom<&String> for SignatureBytes { type Error = CryptoError; fn try_from(signature: &String) -> Result<Self, CryptoError> { Self::try_from(signature as &str) } }
Err(CryptoError::MalformedSignature { algorithm: AlgorithmId::Ed25519, sig_bytes: signature_bytes.clone(), internal_error: format!( "Incorrect signature length: expected {}, got {}.", SignatureBytes::SIZE, signature_bytes.len() ), })
call_expression
[]
Rust
src/output.rs
goto-bus-stop/sqc
43e7b5f00d974036326797470f495392691ffa6b
use crate::highlight::SqlHighlighter; use comfy_table::{Cell, Color, ContentArrangement, Table}; use csv::{ByteRecord, Writer, WriterBuilder}; use itertools::Itertools; use rusqlite::types::ValueRef; use rusqlite::{Row, Statement}; use std::fs::File; use std::io::Write; use std::process::{Command, Stdio}; use std::str::FromStr; use termcolor::{StandardStream, WriteColor}; pub enum OutputTarget { Stdout(StandardStream), File(File), } impl OutputTarget { pub fn start(&mut self) -> Box<dyn WriteColor + '_> { match self { OutputTarget::Stdout(stream) => Box::new(stream.lock()), OutputTarget::File(file) => Box::new(WriteColorFile(file)), } } } struct WriteColorFile<'f>(&'f mut File); impl<'f> std::io::Write for WriteColorFile<'f> { fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> { self.0.write(bytes) } fn flush(&mut self) -> std::io::Result<()> { self.0.flush() } } impl<'f> WriteColor for WriteColorFile<'f> { fn supports_color(&self) -> bool { false } fn set_color(&mut self, _: &termcolor::ColorSpec) -> std::io::Result<()> { Ok(()) } fn reset(&mut self) -> std::io::Result<()> { Ok(()) } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum OutputMode { Null, Table, Csv, Sql, } impl OutputMode { pub fn output_rows<'h>( self, statement: &Statement<'_>, highlight: &'h SqlHighlighter, output: &'h mut dyn WriteColor, ) -> Box<dyn OutputRows + 'h> { match self { OutputMode::Null => Box::new(NullOutput), OutputMode::Table => Box::new(TableOutput::new(statement, output)), OutputMode::Sql => Box::new(SqlOutput::new(statement, highlight, output)), OutputMode::Csv => Box::new(CsvOutput::new(statement, output)), } } } impl FromStr for OutputMode { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "null" => Ok(Self::Null), "table" => Ok(Self::Table), "csv" => Ok(Self::Csv), "sql" => Ok(Self::Sql), _ => Err(()), } } } pub trait OutputRows { fn add_row(&mut self, row: &Row<'_>) -> anyhow::Result<()>; fn finish(&mut self) -> anyhow::Result<()>; } pub struct NullOutput; impl OutputRows for NullOutput { fn add_row(&mut self, _row: &Row<'_>) -> anyhow::Result<()> { Ok(()) } fn finish(&mut self) -> anyhow::Result<()> { Ok(()) } } pub struct TableOutput<'a> { table: Table, num_columns: usize, output: &'a mut dyn WriteColor, } impl<'a> TableOutput<'a> { pub fn new(statement: &Statement<'_>, output: &'a mut dyn WriteColor) -> Self { let mut table = Table::new(); table.load_preset("││──╞══╡│ ──┌┐└┘"); let names = statement.column_names(); let num_columns = names.len(); table.set_header(names); Self { table, num_columns, output, } } } fn value_to_cell(value: ValueRef) -> Cell { match value { ValueRef::Null => Cell::new("NULL").fg(Color::DarkGrey), ValueRef::Integer(n) => Cell::new(n).fg(Color::Yellow), ValueRef::Real(n) => Cell::new(n).fg(Color::Yellow), ValueRef::Text(text) => Cell::new(String::from_utf8_lossy(text)), ValueRef::Blob(blob) => { Cell::new(blob.iter().map(|byte| format!("{:02x}", byte)).join(" ")) } } } fn value_to_cell_nocolor(value: ValueRef) -> Cell { match value { ValueRef::Null => Cell::new("NULL"), ValueRef::Integer(n) => Cell::new(n), ValueRef::Real(n) => Cell::new(n), ValueRef::Text(text) => Cell::new(String::from_utf8_lossy(text)), ValueRef::Blob(blob) => { Cell::new(blob.iter().map(|byte| format!("{:02x}", byte)).join(" ")) } } } impl<'a> OutputRows for TableOutput<'a> { fn add_row(&mut self, row: &Row<'_>) -> anyhow::Result<()> { let table_row = (0..self.num_columns) .map(|index| row.get_ref_unwrap(index)) .map(if self.output.supports_color() { value_to_cell } else { value_to_cell_nocolor }); self.table.add_row(table_row); Ok(()) } fn finish(&mut self) -> anyhow::Result<()> { self.table .set_content_arrangement(ContentArrangement::Dynamic); if self.table.get_row(100).is_some() { let mut command = Command::new("less") .stdin(Stdio::piped()) .env("LESSCHARSET", "UTF-8") .spawn()?; writeln!(command.stdin.as_mut().unwrap(), "{}", self.table)?; command.wait()?; } else { writeln!(self.output, "{}", self.table)?; } Ok(()) } } pub struct CsvOutput<'a> { writer: Writer<&'a mut dyn WriteColor>, } impl<'a> CsvOutput<'a> { pub fn new(statement: &Statement<'_>, output: &'a mut dyn WriteColor) -> Self { let mut writer = WriterBuilder::new().has_headers(true).from_writer(output); writer .write_byte_record(&ByteRecord::from(statement.column_names())) .unwrap(); Self { writer } } } impl<'a> OutputRows for CsvOutput<'a> { fn add_row(&mut self, row: &Row<'_>) -> anyhow::Result<()> { for index in 0..row.as_ref().column_count() { let val = row.get_ref_unwrap(index); match val { ValueRef::Null => self.writer.write_field([]), ValueRef::Integer(n) => self.writer.write_field(format!("{}", n)), ValueRef::Real(n) => self.writer.write_field(format!("{}", n)), ValueRef::Text(text) => self.writer.write_field(text), ValueRef::Blob(blob) => self.writer.write_field(blob), }?; } self.writer.write_record(None::<&[u8]>)?; Ok(()) } fn finish(&mut self) -> anyhow::Result<()> { self.writer.flush()?; Ok(()) } } pub struct SqlOutput<'a> { table_name: String, highlighter: &'a SqlHighlighter, output: &'a mut dyn WriteColor, num_columns: usize, } impl<'a> SqlOutput<'a> { pub fn new( statement: &Statement<'_>, highlighter: &'a SqlHighlighter, output: &'a mut dyn WriteColor, ) -> Self { let num_columns = statement.column_count(); Self { table_name: "tbl".to_string(), highlighter, output, num_columns, } } pub fn with_table_name(self, table_name: String) -> Self { Self { table_name, ..self } } fn println(&mut self, sql: &str) -> std::io::Result<()> { if self.output.supports_color() { writeln!(self.output, "{}", self.highlighter.highlight(sql).unwrap()) } else { writeln!(self.output, "{}", sql) } } } impl<'a> OutputRows for SqlOutput<'a> { fn add_row(&mut self, row: &Row<'_>) -> anyhow::Result<()> { let mut sql = format!("INSERT INTO {} VALUES(", &self.table_name); for index in 0..self.num_columns { use std::fmt::Write; if index > 0 { sql.push_str(", "); } match row.get_ref(index)? { ValueRef::Null => sql.push_str("NULL"), ValueRef::Integer(n) => write!(&mut sql, "{}", n).unwrap(), ValueRef::Real(n) => write!(&mut sql, "{}", n).unwrap(), ValueRef::Text(text) => { write!(&mut sql, "'{}'", std::str::from_utf8(text).unwrap()).unwrap() } ValueRef::Blob(blob) => write!( &mut sql, "X'{}'", blob.iter() .map(|byte| format!("{:02x}", byte)) .collect::<String>() ) .unwrap(), } } sql.push_str(");"); self.println(&sql)?; Ok(()) } fn finish(&mut self) -> anyhow::Result<()> { Ok(()) } }
use crate::highlight::SqlHighlighter; use comfy_table::{Cell, Color, ContentArrangement, Table}; use csv::{ByteRecord, Writer, WriterBuilder}; use itertools::Itertools; use rusqlite::types::ValueRef; use rusqlite::{Row, Statement}; use std::fs::File; use std::io::Write; use std::process::{Command, Stdio}; use std::str::FromStr; use termcolor::{StandardStream, WriteColor}; pub enum OutputTarget { Stdout(StandardStream), File(File), } impl OutputTarget { pub fn start(&mut self) -> Box<dyn WriteColor + '_> { match self { OutputTarget::Stdout(stream) => Box::new(stream.lock()), OutputTarget::File(file) => Box::new(WriteColorFile(file)), } } } struct WriteColorFile<'f>(&'f mut File); impl<'f> std::io::Write for WriteColorFile<'f> { fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> { self.0.write(bytes) } fn flush(&mut self) -> std::io::Result<()> { self.0.flush() } } impl<'f> WriteColor for WriteColorFile<'f> { fn supports_color(&self) -> bool { false } fn set_color(&mut self, _: &termcolor::ColorSpec) -> std::io::Result<()> { Ok(()) } fn reset(&mut self) -> std::io::Result<()> { Ok(()) } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum OutputMode { Null, Table, Csv, Sql, } impl OutputMode { pub fn output_rows<'h>( self, statement: &Statement<'_>, highlight: &'h SqlHighlighter, output: &'h mut dyn WriteColor, ) -> Box<dyn OutputRows + 'h> { match self { OutputMode::Null => Box::new(NullOutput), OutputMode::Table => Box::new(TableOutput::new(statement, output)), OutputMode::Sql => Box::new(SqlOutput::new(statement, highlight, output)), OutputMode::Csv => Box::new(CsvOutput::new(statement, output)), } } } impl FromStr for OutputMode { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "null" => Ok(Self::Null), "table" => Ok(Self::Table), "csv" => Ok(Self::Csv), "sql" => Ok(Self::Sql), _ => Err(()), } } } pub trait OutputRows { fn add_row(&mut self, row: &Row<'_>) -> anyhow::Result<()>; fn finish(&mut self) -> anyhow::Result<()>; } pub struct NullOutput; impl OutputRows for NullOutput { fn add_row(&mut self, _row: &Row<'_>) -> anyhow::Result<()> { Ok(()) } fn finish(&mut self) -> anyhow::Result<()> { Ok(()) } } pub struct TableOutput<'a> { table: Table, num_columns: usize, output: &'a mut dyn WriteColor, } impl<'a> TableOutput<'a> { pub fn new(statement: &Statement<'_>, output: &'a mut dyn WriteColor) -> Self { let mut table = Table::new(); table.load_preset("││──╞══╡│ ──┌┐└┘"); let names = statement.column_names(); let num_columns = names.len(); table.set_header(names); Self { table, num_columns, output, } } } fn value_to_cell(value: ValueRef) -> Cell { match value { ValueRef::Null => Cell::new("NULL").fg(Color::DarkGrey), ValueRef::Integer(n) => Cell::new(n).fg(Color::Yellow), ValueRef::Real(n) => Cell::new(n).fg(Color::Yellow), ValueRef::Text(text) => Cell::new(String::from_utf8_lossy(text)), ValueRef::Blob(blob) => { Cell::new(blob.iter().map(|byte| format!("{:02x}", byte)).join(" ")) } } } fn value_to_cell_nocolor(value: ValueRef) -> Cell { match value { ValueRef::Null => Cell::new("NULL"), ValueRef::Integer(n) => Cell::new(n), ValueRef::Real(n) => Cell::new(n), ValueRef::Text(text) => Cell::new(String::from_utf8_lossy(text)), ValueRef::Blob(blob) => { Cell::new(blob.iter().map(|byte| format!("{:02x}", byte)).join(" ")) } } } impl<'a> OutputRows for TableOutput<'a> { fn add_row(&mut self, row: &Row<'_>) -> anyhow::Result<()> { let table_row = (0..self.num_columns) .map(|index| row.get_ref_unwrap(index)) .map(if self.output.supports_color() { value_to_cell } else { value_to_cell_nocolor }); self.table.add_row(table_row); Ok(()) } fn finish(&mut self) -> anyhow::Result<()> { self.table .set_content_arrangement(ContentArrangement::Dynami
} pub struct CsvOutput<'a> { writer: Writer<&'a mut dyn WriteColor>, } impl<'a> CsvOutput<'a> { pub fn new(statement: &Statement<'_>, output: &'a mut dyn WriteColor) -> Self { let mut writer = WriterBuilder::new().has_headers(true).from_writer(output); writer .write_byte_record(&ByteRecord::from(statement.column_names())) .unwrap(); Self { writer } } } impl<'a> OutputRows for CsvOutput<'a> { fn add_row(&mut self, row: &Row<'_>) -> anyhow::Result<()> { for index in 0..row.as_ref().column_count() { let val = row.get_ref_unwrap(index); match val { ValueRef::Null => self.writer.write_field([]), ValueRef::Integer(n) => self.writer.write_field(format!("{}", n)), ValueRef::Real(n) => self.writer.write_field(format!("{}", n)), ValueRef::Text(text) => self.writer.write_field(text), ValueRef::Blob(blob) => self.writer.write_field(blob), }?; } self.writer.write_record(None::<&[u8]>)?; Ok(()) } fn finish(&mut self) -> anyhow::Result<()> { self.writer.flush()?; Ok(()) } } pub struct SqlOutput<'a> { table_name: String, highlighter: &'a SqlHighlighter, output: &'a mut dyn WriteColor, num_columns: usize, } impl<'a> SqlOutput<'a> { pub fn new( statement: &Statement<'_>, highlighter: &'a SqlHighlighter, output: &'a mut dyn WriteColor, ) -> Self { let num_columns = statement.column_count(); Self { table_name: "tbl".to_string(), highlighter, output, num_columns, } } pub fn with_table_name(self, table_name: String) -> Self { Self { table_name, ..self } } fn println(&mut self, sql: &str) -> std::io::Result<()> { if self.output.supports_color() { writeln!(self.output, "{}", self.highlighter.highlight(sql).unwrap()) } else { writeln!(self.output, "{}", sql) } } } impl<'a> OutputRows for SqlOutput<'a> { fn add_row(&mut self, row: &Row<'_>) -> anyhow::Result<()> { let mut sql = format!("INSERT INTO {} VALUES(", &self.table_name); for index in 0..self.num_columns { use std::fmt::Write; if index > 0 { sql.push_str(", "); } match row.get_ref(index)? { ValueRef::Null => sql.push_str("NULL"), ValueRef::Integer(n) => write!(&mut sql, "{}", n).unwrap(), ValueRef::Real(n) => write!(&mut sql, "{}", n).unwrap(), ValueRef::Text(text) => { write!(&mut sql, "'{}'", std::str::from_utf8(text).unwrap()).unwrap() } ValueRef::Blob(blob) => write!( &mut sql, "X'{}'", blob.iter() .map(|byte| format!("{:02x}", byte)) .collect::<String>() ) .unwrap(), } } sql.push_str(");"); self.println(&sql)?; Ok(()) } fn finish(&mut self) -> anyhow::Result<()> { Ok(()) } }
c); if self.table.get_row(100).is_some() { let mut command = Command::new("less") .stdin(Stdio::piped()) .env("LESSCHARSET", "UTF-8") .spawn()?; writeln!(command.stdin.as_mut().unwrap(), "{}", self.table)?; command.wait()?; } else { writeln!(self.output, "{}", self.table)?; } Ok(()) }
function_block-function_prefixed
[ { "content": "pub fn parse_sql(sql: &str) -> anyhow::Result<ParsedSql<'_>> {\n\n let mut parser = Parser::new();\n\n parser.set_language(tree_sitter_sqlite::language())?;\n\n let tree = parser.parse(sql, None).unwrap();\n\n Ok(ParsedSql { tree, source: sql })\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\...
Rust
lapce-data/src/buffer/decoration.rs
porkotron/lapce
a46fb40e8b9aabf7dcf2ea593ea68e3e025892b6
use druid::{ExtEventSink, Target, WidgetId}; use lapce_core::syntax::Syntax; use lapce_rpc::style::{LineStyles, Style}; use std::{ cell::RefCell, path::PathBuf, rc::Rc, sync::{ atomic::{self}, Arc, }, }; use xi_rope::{rope::Rope, spans::Spans, RopeDelta}; use crate::{ buffer::{data::BufferData, rope_diff, BufferContent, LocalBufferKind}, command::{LapceUICommand, LAPCE_UI_COMMAND}, find::{Find, FindProgress}, }; #[derive(Clone)] pub struct BufferDecoration { pub(super) loaded: bool, pub(super) local: bool, pub(super) find: Rc<RefCell<Find>>, pub(super) find_progress: Rc<RefCell<FindProgress>>, pub(super) syntax: Option<Syntax>, pub(super) line_styles: Rc<RefCell<LineStyles>>, pub(super) semantic_styles: Option<Arc<Spans<Style>>>, pub(super) histories: im::HashMap<String, Rope>, pub(super) tab_id: WidgetId, pub(super) event_sink: ExtEventSink, } impl BufferDecoration { pub fn syntax(&self) -> Option<&Syntax> { self.syntax.as_ref() } pub fn update_styles(&mut self, delta: &RopeDelta) { if let Some(styles) = self.semantic_styles.as_mut() { Arc::make_mut(styles).apply_shape(delta); } else if let Some(syntax) = self.syntax.as_mut() { if let Some(styles) = syntax.styles.as_mut() { Arc::make_mut(styles).apply_shape(delta); } } if let Some(syntax) = self.syntax.as_mut() { syntax.lens.apply_delta(delta); } self.line_styles.borrow_mut().clear(); } pub fn notify_special(&self, buffer: &BufferData) { match &buffer.content { BufferContent::File(_) => {} BufferContent::Local(local) => { let s = buffer.rope.to_string(); match local { LocalBufferKind::Search => { let _ = self.event_sink.submit_command( LAPCE_UI_COMMAND, LapceUICommand::UpdateSearch(s), Target::Widget(self.tab_id), ); } LocalBufferKind::SourceControl => {} LocalBufferKind::Empty => {} LocalBufferKind::FilePicker => { let pwd = PathBuf::from(s); let _ = self.event_sink.submit_command( LAPCE_UI_COMMAND, LapceUICommand::UpdatePickerPwd(pwd), Target::Widget(self.tab_id), ); } LocalBufferKind::Keymap => { let _ = self.event_sink.submit_command( LAPCE_UI_COMMAND, LapceUICommand::UpdateKeymapsFilter(s), Target::Widget(self.tab_id), ); } LocalBufferKind::Settings => { let _ = self.event_sink.submit_command( LAPCE_UI_COMMAND, LapceUICommand::UpdateSettingsFilter(s), Target::Widget(self.tab_id), ); } } } BufferContent::Value(_) => {} } } pub fn notify_update(&self, buffer: &BufferData, delta: Option<&RopeDelta>) { self.trigger_syntax_change(buffer, delta); self.trigger_history_change(buffer); } fn trigger_syntax_change(&self, buffer: &BufferData, delta: Option<&RopeDelta>) { if let BufferContent::File(path) = &buffer.content { if let Some(syntax) = self.syntax.clone() { let path = path.clone(); let rev = buffer.rev; let text = buffer.rope.clone(); let delta = delta.cloned(); let atomic_rev = buffer.atomic_rev.clone(); let event_sink = self.event_sink.clone(); let tab_id = self.tab_id; rayon::spawn(move || { if atomic_rev.load(atomic::Ordering::Acquire) != rev { return; } let new_syntax = syntax.parse(rev, text, delta); if atomic_rev.load(atomic::Ordering::Acquire) != rev { return; } let _ = event_sink.submit_command( LAPCE_UI_COMMAND, LapceUICommand::UpdateSyntax { path, rev, syntax: new_syntax, }, Target::Widget(tab_id), ); }); } } } fn trigger_history_change(&self, buffer: &BufferData) { if let BufferContent::File(path) = &buffer.content { if let Some(head) = self.histories.get("head") { let id = buffer.id; let rev = buffer.rev; let atomic_rev = buffer.atomic_rev.clone(); let path = path.clone(); let left_rope = head.clone(); let right_rope = buffer.rope.clone(); let event_sink = self.event_sink.clone(); let tab_id = self.tab_id; rayon::spawn(move || { if atomic_rev.load(atomic::Ordering::Acquire) != rev { return; } let changes = rope_diff(left_rope, right_rope, rev, atomic_rev.clone()); if changes.is_none() { return; } let changes = changes.unwrap(); if atomic_rev.load(atomic::Ordering::Acquire) != rev { return; } let _ = event_sink.submit_command( LAPCE_UI_COMMAND, LapceUICommand::UpdateHistoryChanges { id, path, rev, history: "head".to_string(), changes: Arc::new(changes), }, Target::Widget(tab_id), ); }); } } } }
use druid::{ExtEventSink, Target, WidgetId}; use lapce_core::syntax::Syntax; use lapce_rpc::style::{LineStyles, Style}; use std::{ cell::RefCell, path::PathBuf, rc::Rc, sync::{ atomic::{self}, Arc, }, }; use xi_rope::{rope::Rope, spans::Spans, RopeDelta}; use crate::{ buffer::{data::BufferData, rope_diff, BufferContent, LocalBufferKind}, command::{LapceUICommand, LAPCE_UI_COMMAND}, find::{Find, FindProgress}, }; #[derive(Clone)] pub struct BufferDecoration { pub(super) loaded: bool, pub(super) local: bool, pub(super) find: Rc<RefCell<Find>>, pub(super) find_progress: Rc<RefCell<FindProgress>>, pub(super) syntax: Option<Syntax>, pub(super) line_styles: Rc<RefCell<LineStyles>>, pub(super) semantic_styles: Option<Arc<Spans<Style>>>, pub(super) histories: im::HashMap<String, Rope>, pub(super) tab_id: WidgetId, pub(super) event_sink: ExtEventSink, } impl BufferDecoration { pub fn syntax(&self) -> Option<&Syntax> { self.syntax.as_ref() } pub fn update_styles(&mut self, delta: &RopeDelta) { if let Some(styles) = self.semantic_styles.as_mut() { Arc::make_mut(styles).apply_shape(delta); } else if let Some(syntax) = self.syntax.as_mut() { if let Some(styles) = syntax.styles.as_mut() { Arc::make_mut(styles).apply_shape(delta); } } if let Some(syntax) = self.syntax.as_mut() { syntax.lens.apply_delta(delta); } self.line_styles.borrow_mut().clear(); } pub fn notify_special(&self, buffer: &BufferData) { match &buffer.content { BufferContent::File(_) => {} BufferContent::Local(local) => { let s = buffer.rope.to_string(); match local { LocalBufferKind::Search => { let _ = self.event_sink.submit_command( LAPCE_UI_COMMAND, LapceUICommand::UpdateSearch(s), Target::Widget(self.tab_id), ); } LocalBufferKind::SourceControl => {} LocalBufferKind::Empty => {} LocalBufferKind::FilePicker => { let pwd = PathBuf::from(s); let _ = self.event_sink.submit_command( LAPCE_UI_COMMAND, LapceUICommand::UpdatePickerPwd(pwd), Target::Widget(self.tab_id), ); } LocalBufferKind::Keymap => { let _ = self.event_sink.submit_command( LAPCE_UI_COMMAND, LapceUICommand::UpdateKeymapsFilter(s), Target::Widget(self.tab_id), ); } LocalBufferKind::Settings => { let _ = self.event_sink.submit_command( LAPCE_UI_COMMAND, LapceUICommand::UpdateSettingsFilter(s), Target::Widget(self.tab_id), ); } } } BufferContent::Value(_) => {} } } pub fn notify_update(&self, buffer: &BufferData, delta: Option<&RopeDelta>) { self.trigger_syntax_change(buffer, delta); self.trigger_history_change(buffer); } fn trigger_syntax_change(&self, buffer: &BufferData, delta: Option<&RopeDelta>) { if let BufferContent::File(path) = &buffer.content { if let Some(syntax) = self.syntax.clone() { let path = path.clone(); let rev = buffer.rev; let text = buffer.rope.clone(); let delta = delta.cloned(); let atomic_rev = buffer.atomic_rev.clone(); let event_sink = self.event_sink.clone(); let tab_id = self.tab_id; rayon::spawn(move || { if atomic_rev.load(atomic::Ordering::Acquire) != rev { return; } let new_syntax = syntax.parse(rev, text, delta); if atomic_rev.load(atomic::Ordering::Acquire) != rev { return; } let _ = event_sink.submit_command( LAPCE_UI_COMMAND, LapceUICommand::UpdateSyntax { path, rev, syntax: new_syntax, }, Target::Widget(tab_id), ); }); } } } fn trigger_history_change(&self, buffer: &BufferData) { if let BufferContent::File(path) = &buffer.content { if let Some(head) = self.histories.get("head") { let id = buffer.id; let rev = buffer.rev; let atomic_rev = buffer.atomic_rev.clone(); let path = path.clone(); let left_rope = head.clone(); let right_rope = buffer.rope.clone(); let event_sink = self.event_sink.clone(); let tab_id = self.tab_id; rayon::spawn(move || { if atomic_rev.load(atomic::Ordering::Acquire) != rev { return; } let changes = rope_diff(left_rope, right_rope, rev, atomic_rev.clone());
}
if changes.is_none() { return; } let changes = changes.unwrap(); if atomic_rev.load(atomic::Ordering::Acquire) != rev { return; } let _ = event_sink.submit_command( LAPCE_UI_COMMAND, LapceUICommand::UpdateHistoryChanges { id, path, rev, history: "head".to_string(), changes: Arc::new(changes), }, Target::Widget(tab_id), ); }); } } }
function_block-function_prefix_line
[ { "content": "fn load_file(path: &Path) -> Result<Rope> {\n\n let mut f = File::open(path)?;\n\n let mut bytes = Vec::new();\n\n f.read_to_end(&mut bytes)?;\n\n Ok(Rope::from(std::str::from_utf8(&bytes)?))\n\n}\n\n\n", "file_path": "lapce-proxy/src/buffer.rs", "rank": 0, "score": 260806....
Rust
test/datalog_tests/rust_api_test/src/main.rs
lykahb/differential-datalog
bf8b86468476a1ee3560e5f58ee91b44565c78f7
use std::borrow::Cow; use tutorial_ddlog::Relations; use tutorial_ddlog::typedefs::*; use differential_datalog::api::HDDlog; use differential_datalog::{DDlog, DDlogDynamic, DDlogInventory}; use differential_datalog::program::config::{Config, ProfilingConfig}; use differential_datalog::DeltaMap; use differential_datalog::ddval::DDValConvert; use differential_datalog::ddval::DDValue; use differential_datalog::program::RelId; use differential_datalog::program::Update; use differential_datalog::record::Record; use differential_datalog::record::RelIdentifier; use differential_datalog::record::UpdCmd; fn main() -> Result<(), String> { let config = Config::new() .with_timely_workers(1) .with_profiling_config(ProfilingConfig::SelfProfiling); let (hddlog, init_state) = tutorial_ddlog::run_with_config(config, false)?; println!("Initial state"); dump_delta(&hddlog, &init_state); /* * We perform two transactions that insert in the following two DDlog relations * (see `tutorial.dl`): * * ``` * input relation Word1(word: string, cat: Category) * input relation Word2(word: string, cat: Category) * ``` * * The first transactio uses the type-safe API, which should be preferred when * writing a client bound to a specific known DDlog program. * * The second transaction uses the dynamically typed record API. */ hddlog.transaction_start()?; let updates = vec![ Update::Insert { relid: Relations::Word1 as RelId, v: Word1 { word: "foo-".to_string(), cat: Category::CategoryOther, } .into_ddvalue(), }, Update::Insert { relid: Relations::Word2 as RelId, v: Word2 { word: "bar".to_string(), cat: Category::CategoryOther, } .into_ddvalue(), }, ]; hddlog.apply_updates(&mut updates.into_iter())?; let mut delta = hddlog.transaction_commit_dump_changes()?; println!("\nState after transaction 1"); dump_delta(&hddlog, &delta); println!("\nEnumerating new phrases"); let new_phrases = delta.get_rel(Relations::Phrases as RelId); for (val, weight) in new_phrases.iter() { assert_eq!(*weight, 1); let phrase: &Phrases = Phrases::from_ddvalue_ref(val); println!("New phrase: {}", phrase.phrase); } hddlog.transaction_start()?; let relid_word1 = hddlog.inventory.get_table_id("Word1").unwrap() as RelId; let commands = vec![UpdCmd::Insert( RelIdentifier::RelId(relid_word1), Record::PosStruct( Cow::from("Word1"), vec![ Record::String("buzz".to_string()), Record::PosStruct(Cow::from("CategoryOther"), vec![]), ], ), )]; hddlog.apply_updates_dynamic(&mut commands.into_iter())?; let delta = hddlog.transaction_commit_dump_changes()?; println!("\nState after transaction 2"); dump_delta(&hddlog, &delta); hddlog.stop().unwrap(); Ok(()) } fn dump_delta(ddlog: &HDDlog, delta: &DeltaMap<DDValue>) { for (rel, changes) in delta.iter() { println!("Changes to relation {}", ddlog.inventory.get_table_name(*rel).unwrap()); for (val, weight) in changes.iter() { println!("{} {:+}", val, weight); } } }
use std::borrow::Cow; use tutorial_ddlog::Relations; use tutorial_ddlog::typedefs::*; use differential_datalog::api::HDDlog; use differential_datalog::{DDlog, DDlogDynamic, DDlogInventory}; use differential_datalog::program::config::{Config, ProfilingConfig}; use differential_datalog::DeltaMap; use differential_datalog::ddval::DDValConvert; use differential_datalog::ddval::DDValue; use differential_datalog::program::RelId; use differential_datalog::program::Update; use differential_datalog::record::Record; use differential_datalog::record::RelIdentifier; use differential_datalog::record::UpdCmd; fn main() -> Result<(), String> { let config = Config::new() .with_timely_workers(1) .with_profiling_config(ProfilingConfig::SelfProfiling); let (hddlog, init_state) = tutorial_ddlog::run_with_config(config, false)?; println!("Initial state"); dump_delta(&hddlog, &init_state); /* * We perform two transactions that insert in the following two DDlog relations * (see `tutorial.dl`): * * ``` * input relation Word1(word: string, cat: Category) * input relation Word2(word: string, cat: Category) * ``` * * The first transactio uses the type-safe API, which should be preferred when * writing a client bound to a specific known DDlog program. * * The second transaction uses the dynamically typed record API. */ hddlog.transaction_start()?; let updates = vec![ Update::Insert { relid: Relations::Word1 as RelId, v: Word1 { word: "foo-".to_string(), cat: Category::CategoryOther, } .into_ddvalue(), }, Update::Insert { relid: Relations::Word2 as RelId, v: Word2 { word: "bar".to_string(), cat: Category::CategoryOther, } .into_ddvalue(), }, ]; hddlog.apply_updates(&mut updates.into_iter())?; let mut delta = hddlog.transaction_commit_dump_changes()?; println!("\nState after transaction 1"); dump_delta(&hddlog, &delta); println!("\nEnumerating new phrases"); let new_phrases = delta.get_rel(Relations::Phrases as RelId); for (val, weight) in new_phrases.iter() { assert_eq!(*weight, 1); let phrase: &Phrases = Phrases::from_ddvalue_ref(val); println!("New phrase: {}", phrase.phrase); } hddlog.transaction_start()?; let relid_word1 = hddlog.inventory.get_table_id("Word1").unwrap() as RelId; let commands = vec![UpdCmd::Insert( RelIdentifier::RelId(relid_word1), Record::PosStruct( Cow::from("Word1"), vec![ Record::String("buzz".to_string()), Record::PosStruct(Cow::from("CategoryOther"), vec![]), ], ), )]; hddlog.apply_updates_dynamic(&mut commands.into_iter())?; let delta = hddlog.transaction_commit_dump_changes()?; println!("\nState after transaction 2"); dump_delta(&hddlog, &delta); hddlog.stop().unwrap(); Ok(()) }
fn dump_delta(ddlog: &HDDlog, delta: &DeltaMap<DDValue>) { for (rel, changes) in delta.iter() { println!("Changes to relation {}", ddlog.inventory.get_table_name(*rel).unwrap()); for (val, weight) in changes.iter() { println!("{} {:+}", val, weight); } } }
function_block-full_function
[ { "content": "fn record_from_array(mut src: Vec<Value>) -> Result<Record, String> {\n\n if src.len() != 2 {\n\n return Err(format!(\"record array is not of length 2: {:?}\", src));\n\n };\n\n let val = src.remove(1);\n\n let field = src.remove(0);\n\n match field {\n\n Value::String...
Rust
src/common/parse.rs
Nejat/cli-toolbox-rs
646a0b7de8fe2898b17e492e9310eda34c9e845d
use syn::{Error, Expr}; #[cfg(any(feature = "debug", feature = "report"))] use syn::Lit; use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; #[cfg(any(feature = "eval", feature = "release"))] use verbosity::Verbosity; #[cfg(any(feature = "eval", feature = "release"))] use crate::common::{DUPE_VERBOSITY_ERR, QUITE_ERR, VERBOSITY_ORDER_ERR}; #[cfg(any(feature = "eval", feature = "release"))] use crate::common::kw; #[cfg(any(feature = "debug", feature = "report"))] use crate::common::Message; #[cfg(any(feature = "debug", feature = "report"))] impl Message { pub fn parse(input: ParseStream, ln_brk: bool) -> syn::Result<Self> { Ok(Self { fmt: parse_format(input)?, args: parse_args(input)?, ln_brk, }) } } #[cfg(any(feature = "debug", feature = "eval", feature = "release", feature = "report"))] pub fn decode_expr_type(expr: &Expr) -> &'static str { match expr { Expr::Array(_) => "array", Expr::Assign(_) => "assign", Expr::AssignOp(_) => "assign-op", Expr::Async(_) => "async", Expr::Await(_) => "await", Expr::Binary(_) => "binary", Expr::Block(_) => "block", Expr::Box(_) => "box", Expr::Break(_) => "break", Expr::Call(_) => "call", Expr::Cast(_) => "cast", Expr::Closure(_) => "closure", Expr::Continue(_) => "continue", Expr::Field(_) => "field", Expr::ForLoop(_) => "for-loop", Expr::Group(_) => "group", Expr::If(_) => "if", Expr::Index(_) => "index", Expr::Let(_) => "let", Expr::Lit(_) => "lit", Expr::Loop(_) => "loop", Expr::Macro(_) => "macro", Expr::Match(_) => "match", Expr::MethodCall(_) => "method call", Expr::Paren(_) => "paren", Expr::Path(_) => "path", Expr::Range(_) => "range", Expr::Reference(_) => "reference", Expr::Repeat(_) => "repeat", Expr::Return(_) => "return", Expr::Struct(_) => "struct", Expr::Try(_) => "try", Expr::TryBlock(_) => "try-block", Expr::Tuple(_) => "tuple", Expr::Type(_) => "type", Expr::Unary(_) => "unary", Expr::Unsafe(_) => "unsafe", Expr::Verbatim(_) => "verbatim", Expr::While(_) => "while", Expr::Yield(_) => "yield", Expr::__TestExhaustive(_) => unimplemented!() } } #[cfg(any(feature = "eval", feature = "release"))] #[allow(clippy::shadow_unrelated)] pub fn parse_expr_eval<T>( input: ParseStream, macro_name: &str, builder: impl Fn(Option<Expr>, Option<Expr>) -> T, ) -> syn::Result<T> { let verbosity = parse_verbosity(input, false)?; let expr = parse_expression(input, macro_name)?; let error_span = input.span(); match verbosity { Some(Verbosity::Quite) => unreachable!(QUITE_ERR), Some(Verbosity::Terse) | None => { let verbose = if let Ok(Some(verbose)) = parse_verbosity(input, true) { verbose } else { return Ok(builder(Some(expr), None)); }; match verbose { Verbosity::Quite => unreachable!(QUITE_ERR), Verbosity::Terse => Err(Error::new(error_span, DUPE_VERBOSITY_ERR)), Verbosity::Verbose => Ok(builder(Some(expr), Some(parse_expression(input, macro_name)?))) } } Some(Verbosity::Verbose) => { if input.is_empty() { Ok(builder(None, Some(expr))) } else { let error_span = input.span(); match parse_verbosity(input, true) { Ok(verbosity) => { match verbosity { Some(Verbosity::Quite) => unreachable!(QUITE_ERR), Some(Verbosity::Terse) => Err(Error::new(error_span, VERBOSITY_ORDER_ERR)), Some(Verbosity::Verbose) => Err(Error::new(error_span, DUPE_VERBOSITY_ERR)), None => Err(Error::new(error_span, "unexpected token")) } } Err(err) => Err(err) } } } } } #[cfg(any(feature = "debug", feature = "eval", feature = "release"))] pub fn parse_expression(input: ParseStream, macro_name: &str) -> syn::Result<Expr> { let expr = <Expr>::parse(input)?; match expr { Expr::Block(_) | Expr::TryBlock(_) | Expr::Unsafe(_) => {} Expr::Array(_) | Expr::Assign(_) | Expr::AssignOp(_) | Expr::Await(_) | Expr::Binary(_) | Expr::Box(_) | Expr::Break(_) | Expr::Call(_) | Expr::Cast(_) | Expr::Closure(_) | Expr::Continue(_) | Expr::Field(_) | Expr::Group(_) | Expr::If(_) | Expr::Index(_) | Expr::Macro(_) | Expr::Match(_) | Expr::MethodCall(_) | Expr::Path(_) | Expr::Reference(_) | Expr::Repeat(_) | Expr::Return(_) | Expr::Try(_) | Expr::Tuple(_) | Expr::Unary(_) => parse_optional_semicolon(input, false)?, _ => return Err(Error::new( expr.span(), format!( "{:?} is not a supported {} expression, try placing it into a code block", decode_expr_type(&expr), macro_name ), )) } Ok(expr) } #[cfg(any(feature = "debug", feature = "eval", feature = "release", feature = "report"))] pub fn parse_optional_semicolon(input: ParseStream, required: bool) -> syn::Result<()> { if input.peek(Token![;]) || (required && input.peek(Token![@])) { <Token![;]>::parse(input)?; } Ok(()) } #[cfg(any(feature = "eval", feature = "release"))] pub fn parse_verbosity(input: ParseStream, chk_semicolon: bool) -> syn::Result<Option<Verbosity>> { let verbosity; let span = input.span(); if chk_semicolon { parse_optional_semicolon(input, false)?; } if input.peek(Token![@]) { if verbosity_keyword_peek2(input) { <Token![@]>::parse(input)?; if input.peek(kw::terse) { <kw::terse>::parse(input)?; verbosity = Some(Verbosity::Terse); } else { <kw::verbose>::parse(input)?; verbosity = Some(Verbosity::Verbose); } } else { return Err(Error::new( span, "invalid verbosity designation, use @terse, @verbose or leave blank for default level", )); } } else { verbosity = None; } Ok(verbosity) } #[cfg(any(feature = "debug", feature = "report"))] fn parse_args(input: ParseStream) -> syn::Result<Option<Vec<Expr>>> { let mut exprs = Vec::new(); while input.peek(Token![,]) { <Token![,]>::parse(input)?; let expr = <Expr>::parse(input)?; match expr { Expr::Array(_) | Expr::Await(_) | Expr::Binary(_) | Expr::Block(_) | Expr::Call(_) | Expr::Cast(_) | Expr::Field(_) | Expr::Group(_) | Expr::If(_) | Expr::Index(_) | Expr::Lit(_) | Expr::Macro(_) | Expr::Match(_) | Expr::MethodCall(_) | Expr::Paren(_) | Expr::Path(_) | Expr::Range(_) | Expr::Reference(_) | Expr::Repeat(_) | Expr::Try(_) | Expr::TryBlock(_) | Expr::Tuple(_) | Expr::Unary(_) | Expr::Unsafe(_) => {} _ => return Err(Error::new( expr.span(), format!("{:?} is not a supported arg expression", decode_expr_type(&expr)), )) } exprs.push(expr); } parse_optional_semicolon(input, true)?; Ok(if exprs.is_empty() { None } else { Some(exprs) }) } #[cfg(any(feature = "debug", feature = "report"))] fn parse_format(input: ParseStream) -> syn::Result<Lit> { let literal = <Lit>::parse(input)?; match literal { Lit::Str(_) | Lit::ByteStr(_) => {} _ => return Err(Error::new(literal.span(), "expecting a string literal")) } Ok(literal) } #[cfg(any(feature = "eval", feature = "release"))] fn verbosity_keyword_peek2(input: ParseStream) -> bool { input.peek2(kw::terse) || input.peek2(kw::verbose) }
use syn::{Error, Expr}; #[cfg(any(feature = "debug", feature = "report"))] use syn::Lit; use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; #[cfg(any(feature = "eval", feature = "release"))] use verbosity::Verbosity; #[cfg(any(feature = "eval", feature = "release"))] use crate::common::{DUPE_VERBOSITY_ERR, QUITE_ERR, VERBOSITY_ORDER_ERR}; #[cfg(any(feature = "eval", feature = "release"))] use crate::common::kw; #[cfg(any(feature = "debug", feature = "report"))] use crate::common::Message; #[cfg(any(feature = "debug", feature = "report"))] impl Message { pub fn parse(input: ParseStream, ln_brk: bool) -> syn::Result<Self> { Ok(Self { fmt: parse_format(input)?, args: parse_args(input)?, ln_brk, }) } } #[cfg(any(feature = "debug", feature = "eval", feature = "release", feature = "report"))] pub fn decode_expr_type(expr: &Expr) -> &'static str { match expr { Expr::Array(_) => "array", Expr::Assign(_) => "assign", Expr::AssignOp(_) => "assign-op", Expr::Async(_) => "async", Expr::Await(_) => "await", Expr::Binary(_) => "binary", Expr::Block(_) => "block", Expr::Box(_) => "box", Expr::Break(_) => "break", Expr::Call(_) => "call", Expr::Cast(_) => "cast", Expr::Closure(_) => "closure", Expr::Continue(_) => "continue", Expr::Field(_) => "field", Expr::ForLoop(_) => "for-loop", Expr::Group(_) => "group", Expr::If(_) => "if", Expr::Index(_) => "index", Expr::Let(_) => "let", Expr::Lit(_) => "lit", Expr::Loop(_) => "loop", Expr::Macro(_) => "macro", Expr::Match(_) => "match", Expr::MethodCall(_) => "method call", Expr::Paren(_) => "paren", Expr::Path(_) => "path", Expr::Range(_) => "range", Expr::Reference(_) => "reference", Expr::Repeat(_) => "repeat", Expr::Return(_) => "return", Expr::Struct(_) => "struct", Expr::Try(_) => "try", Expr::TryBlock(_) => "try-block", Expr::Tuple(_) => "tuple", Expr::Type(_) => "type", Expr::Unary(_) => "unary", Expr::Unsafe(_) => "unsafe", Expr::Verbatim(_) => "verbatim", Expr::While(_) => "while", Expr::Yield(_) => "yield", Expr::__TestExhaustive(_) => unimplemented!() } } #[cfg(any(feature = "eval", feature = "release"))] #[allow(clippy::shadow_unrelated)] pub fn parse_expr_eval<T>( input: ParseStream, macro_name: &str, builder: impl Fn(Option<Expr>, Option<Expr>) -> T, ) -> syn::Result<T> { let verbosity = parse_verbosity(input, false)?; let expr = parse_expression(input, macro_name)?; let error_span = input.span(); match verbosity { Some(Verbosity::Quite) => unreachable!(QUITE_ERR), Some(Verbosity::Terse) | None => { let verbose = if let Ok(Some(verbose)) = parse_verbosity(input, true) { verbose } else { return Ok(builder(Some(expr), None)); }; match verbose { Verbosity::Quite => unreachable!(QUITE_ERR), Verbosity::Terse => Err(Error::new(error_span, DUPE_VERBOSITY_ERR)), Verbosity::Verbose => Ok(builder(Some(expr), Some(parse_expression(input, macro_name)?))) } } Some(Verbosity::Verbose) => { if input.is_empty() { Ok(builder(None, Some(expr))) } else { let error_span = input.span(); match parse_verbosity(input, true) { Ok(verbosity) => { match verbosity { Some(Verbosity::Quite) => unreachable!(QUITE_ERR), Some(Verbosity::Terse) => Err(Error::new(error_span, VERBOSITY_ORDER_ERR)), Some(Verbosity::Verbose) => Err(Error::new(error_span, DUPE_VERBOSITY_ERR)), None => Err(Error::new(error_span, "unexpected token")) } } Err(err) => Err(err) } } } } } #[cfg(any(feature = "debug", feature = "eval", feature = "release"))] pub fn parse_expression(input: ParseStream, macro_name: &str) -> syn::Result<Expr> { let expr = <Expr>::parse(input)?; match expr { Expr::Block(_) | Expr::TryBlock(_) | Expr::Unsafe(_) => {} Expr::Array(_) | Expr::Assign(_) | Expr::AssignOp(_) | Expr::Await(_) | Expr::Binary(_) | Expr::Box(_) | Expr::Break(_) | Expr::Call(_) | Expr::Cast(_) | Expr::Closure(_) | Expr::Continue(_) | Expr::Field(_) | Expr::Group(_) | Expr::If(_) | Expr::Index(_) | Expr::Macro(_) | Expr::Match(_) | Expr::MethodCall(_) | Expr::Path(_) | Expr::Reference(_) | Expr::Repeat(_) | Expr::Return(_) | Expr::Try(_) | Expr::Tuple(_) | Expr::Unary(_) => parse_optional_semicolon(input, false)?, _ => return Err(Error::new( expr.span(), format!( "{:?} is not a supported {} expression, try placing it into a code block", decode_expr_type(&expr), macro_name ), )) } Ok(expr) } #[cfg(any(feature = "debug", feature = "eval", feature = "release", feature = "report"))] pub fn parse_optional_semicolon(input: ParseStream, required: bool) -> syn::Result<()> { if input.peek(Token![;]) || (required && input.peek(Token![@])) { <Token![;]>::parse(input)?; } Ok(()) } #[cfg(any(feature = "eval", feature = "release"))] pub fn parse_verbosity(input: ParseStream, chk_semicolon: bool) -> syn::Result<Option<Verbosity>> { let verbosity; let span = input.span(); if chk_semicolon { parse_optional_semicolon(input, false)?; } if input.peek(Token![@]) { if verbosity_keyword_peek2(input) { <Token![@]>::parse(input)?; if input.peek(kw::terse) { <kw::terse>::parse(input)?; verbosity = Some(Verbosity::Terse); } else { <kw::verbose>::parse(input)?; verbosity = Some(Verbosity::Verbose); } } else { return Err(Error::new( span, "invalid verbosity designation, use @terse, @verbose or leave blank for default level", )); } } else { verbosity = None; } Ok(verbosity) } #[cfg(any(feature = "debug", feature = "report"))] fn parse_args(input: ParseStream) -> syn::Result<Option<Vec<Expr>>> { let mut exprs = Vec::new(); while input.peek(Token![,]) { <Token![,]>::parse(input)?; let expr = <Expr>::parse(input)?; match expr { Expr::Array(_) | Expr::Await(_) | Expr::Binary(_) | Expr::Block(_) | Expr::Call(_) | Expr::Cast(_) | Expr::Field(_) | Expr::Group(_) | Expr::If(_) | Expr::Index(_) | Expr::Lit(_) | Expr::Macro(_) | Expr::Match(_) | Expr::MethodCall(_) | Expr::Paren(_) | Expr::Path(_) | Expr::Range(_) | Expr::Reference(_) | Expr::Repeat(_) | Expr::Try(_) | Expr::TryBlock(_) | Expr::Tuple(_) | Expr::Unary(_) | Expr::Unsafe(_) => {} _ => return Err(Error::new( expr.span(), format!("{:?} is not a supported arg expression", decode_expr_type(&expr)), )) } exprs.push(expr); } parse_optional_semicolon(input, true)?; Ok(if exprs.is_empty() { None } else { Some(exprs) }) } #[cfg(any(feature = "debug", feature = "report"))] fn parse_format(input: ParseStream) -> syn::Resu
#[cfg(any(feature = "eval", feature = "release"))] fn verbosity_keyword_peek2(input: ParseStream) -> bool { input.peek2(kw::terse) || input.peek2(kw::verbose) }
lt<Lit> { let literal = <Lit>::parse(input)?; match literal { Lit::Str(_) | Lit::ByteStr(_) => {} _ => return Err(Error::new(literal.span(), "expecting a string literal")) } Ok(literal) }
function_block-function_prefixed
[ { "content": "#[cfg(feature = \"eval\")]\n\n#[proc_macro]\n\npub fn eval(input: TokenStream) -> TokenStream {\n\n parse_macro_input!(input as eval_macro::Eval).into_token_stream().into()\n\n}\n\n\n\n/// Conditionally evaluates expressions when intended verbosity matches active verbosity\n\n/// and only when ...
Rust
src/common/mod.rs
samkenxstream/rezolus
e48c39dbeda5277a2a70fab86f114e31df24a861
use std::collections::HashMap; use std::io::BufRead; use std::io::SeekFrom; use dashmap::DashMap; use tokio::fs::File; use tokio::io::{AsyncBufReadExt, AsyncSeekExt, BufReader}; pub mod bpf; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); pub const NAME: &str = env!("CARGO_PKG_NAME"); pub const SECOND: u64 = 1_000 * MILLISECOND; pub const MILLISECOND: u64 = 1_000 * MICROSECOND; pub const MICROSECOND: u64 = 1_000 * NANOSECOND; pub const NANOSECOND: u64 = 1; pub struct HardwareInfo { numa_mapping: DashMap<u64, u64>, } impl HardwareInfo { pub fn new() -> Self { let numa_mapping = DashMap::new(); let mut node = 0; loop { let path = format!("/sys/devices/system/node/node{}/cpulist", node); if let Ok(f) = std::fs::File::open(path) { let mut reader = std::io::BufReader::new(f); let mut line = String::new(); if reader.read_line(&mut line).is_ok() { let ranges: Vec<&str> = line.trim().split(',').collect(); for range in ranges { let parts: Vec<&str> = range.split('-').collect(); if parts.len() == 1 { if let Ok(id) = parts[0].parse() { numa_mapping.insert(id, node); } } else if parts.len() == 2 { if let Ok(start) = parts[0].parse() { if let Ok(stop) = parts[1].parse() { for id in start..=stop { numa_mapping.insert(id, node); } } } } } } } else { break; } node += 1; } Self { numa_mapping } } pub fn get_numa(&self, core: u64) -> Option<u64> { self.numa_mapping.get(&core).map(|v| *v.value()) } } pub fn hardware_threads() -> Result<u64, ()> { let path = "/sys/devices/system/cpu/present"; let f = std::fs::File::open(path).map_err(|e| debug!("failed to open file ({:?}): {}", path, e))?; let mut f = std::io::BufReader::new(f); let mut line = String::new(); f.read_line(&mut line) .map_err(|_| debug!("failed to read line"))?; let line = line.trim(); let a: Vec<&str> = line.split('-').collect(); a.last() .unwrap_or(&"0") .parse::<u64>() .map_err(|e| debug!("could not parse num cpus from file ({:?}): {}", path, e)) .map(|i| i + 1) } pub async fn nested_map_from_file( file: &mut File, ) -> Result<HashMap<String, HashMap<String, u64>>, std::io::Error> { file.seek(SeekFrom::Start(0)).await?; let mut ret = HashMap::<String, HashMap<String, u64>>::new(); let mut reader = BufReader::new(file); let mut keys = String::new(); let mut values = String::new(); while reader.read_line(&mut keys).await? > 0 { if reader.read_line(&mut values).await? > 0 { let mut keys_split = keys.trim().split_whitespace(); let mut values_split = values.trim().split_whitespace(); if let Some(pkey) = keys_split.next() { let _ = values_split.next(); if !ret.contains_key(pkey) { ret.insert(pkey.to_string(), Default::default()); } let inner = ret.get_mut(pkey).unwrap(); for key in keys_split { if let Some(Ok(value)) = values_split.next().map(|v| v.parse()) { inner.insert(key.to_owned(), value); } } } keys.clear(); values.clear(); } } Ok(ret) } pub fn default_percentiles() -> Vec<f64> { vec![1.0, 10.0, 50.0, 90.0, 99.0] } #[allow(dead_code)] pub struct KernelInfo { release: String, } #[allow(dead_code)] impl KernelInfo { pub fn new() -> Result<Self, std::io::Error> { let output = std::process::Command::new("uname").args(["-r"]).output()?; let release = std::str::from_utf8(&output.stdout) .map_err(|_| std::io::Error::from(std::io::ErrorKind::InvalidInput))?; Ok(Self { release: release.to_string(), }) } pub fn release_major(&self) -> Result<u32, std::io::Error> { let parts: Vec<&str> = self.release.split('.').collect(); if let Some(s) = parts.get(0) { return s .parse::<u32>() .map_err(|_| std::io::Error::from(std::io::ErrorKind::InvalidInput)); } Err(std::io::Error::from(std::io::ErrorKind::InvalidInput)) } pub fn release_minor(&self) -> Result<u32, std::io::Error> { let parts: Vec<&str> = self.release.split('.').collect(); if let Some(s) = parts.get(1) { return s .parse::<u32>() .map_err(|_| std::io::Error::from(std::io::ErrorKind::InvalidInput)); } Err(std::io::Error::from(std::io::ErrorKind::InvalidInput)) } }
use std::collections::HashMap; use std::io::BufRead; use std::io::SeekFrom; use dashmap::DashMap; use tokio::fs::File; use tokio::io::{AsyncBufReadExt, AsyncSeekExt, BufReader}; pub mod bpf; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); pub const NAME: &str = env!("CARGO_PKG_NAME"); pub const SECOND: u64 = 1_000 * MILLISECOND; pub const MILLISECOND: u64 = 1_000 * MICROSECOND; pub const MICROSECOND: u64 = 1_000 * NANOSECOND; pub const NANOSECOND: u64 = 1; pub struct HardwareInfo { numa_mapping: DashMap<u64, u64>, } impl HardwareInfo { pub fn new() -> Self { let numa_mapping = DashMap::new(); let mut node = 0; loop { let path = format!("/sys/devices/system/node/node{}/cpulist", node); if let Ok(f) = std::fs::File::open(path) { let mut reader = std::io::BufReader::new(f); let mut line = String::new(); if reader.read_line(&mut line).is_ok() { let ranges: Vec<&str> = line.trim().split(',').collect(); for range in ranges { let parts: Vec<&str> = range.split('-').collect(); if parts.len() == 1 { if let Ok(id) = parts[0].parse() { numa_mapping.insert(id, node); } } else if parts.len() == 2 { if let Ok(start) = parts[0].parse() { if let Ok(stop) = parts[1].parse() { for id in start..=stop { numa_mapping.insert(id, node); } } } } } } } else { break; } node += 1; } Self { numa_mapping } } pub fn get_numa(&self, core: u64) -> Option<u64> { self.numa_mapping.get(&core).map(|v| *v.value()) } } pub fn hardware_threads() -> Result<u64, ()> { let path = "/sys/devices/system/cpu/present"; let f = std::fs::File::open(path).map_err(|e| debug!("failed to open file ({:?}): {}", path, e))?; let mut f = std::io::BufReader::new(f); let mut line = String::new(); f.read_line(&mut line) .map_err(|_| debug!("failed to read line"))?; let line = line.trim(); let a: Vec<&str> = line.split('-').collect(); a.last() .unwrap_or(&"0") .parse::<u64>() .map_err(|e| debug!("could not parse num cpus from file ({:?}): {}", path, e)) .map(|i| i + 1) } pub async fn nested_map_from_file( file: &mut File, ) -> Result<HashMap<String, HashMap<String, u64>>, std::io::Error> { file.seek(SeekFrom::Start(0)).await?; let mut ret = HashMap::<String, HashMap<String, u64>>::new(); let mut reader = BufReader::new(file); let mut keys = String::new(); let mut values = String::new(); while reader.read_line(&mut keys).await? > 0 { if reader.read_line(&mut values).await? > 0 { let mut keys_split = keys.trim().split_whitespace(); let mut values_split = values.trim().split_whitespace(); if let Some(pkey) = keys_split.next() { let _ = values_split.next(); if !ret.contains_key(pkey) { ret.insert(pkey.to_string(), Default::default()); } let inner = ret.get_mut(pkey).unwrap(); for key in keys_split { if let Some(Ok(value)) = values_split.next().map(|v| v.parse()) { inner.insert(key.to_owned(), value); } } } keys.clear(); values.clear(); } } Ok(ret) } pub fn default_percentiles() -> Vec<f64> { vec![1.0, 10.0, 50.0, 90.0, 99.0] } #[allow(dead_code)] pub struct KernelInfo { release: String, } #[allow(dead_code)] impl KernelInfo { pub fn new() -> Result<Self, std::io::Error> { let output = std::process::Command::new("uname").args(["-r"]).output()?; let release = std::str::from_utf8(&output.stdout) .map_err(|_| std::io::Error::from(std::io::ErrorKind::InvalidInput))?; Ok(Self { release: release.to_string(), }) }
pub fn release_minor(&self) -> Result<u32, std::io::Error> { let parts: Vec<&str> = self.release.split('.').collect(); if let Some(s) = parts.get(1) { return s .parse::<u32>() .map_err(|_| std::io::Error::from(std::io::ErrorKind::InvalidInput)); } Err(std::io::Error::from(std::io::ErrorKind::InvalidInput)) } }
pub fn release_major(&self) -> Result<u32, std::io::Error> { let parts: Vec<&str> = self.release.split('.').collect(); if let Some(s) = parts.get(0) { return s .parse::<u32>() .map_err(|_| std::io::Error::from(std::io::ErrorKind::InvalidInput)); } Err(std::io::Error::from(std::io::ErrorKind::InvalidInput)) }
function_block-full_function
[ { "content": "#[cfg(feature = \"bpf\")]\n\npub fn symbol_lookup(name: &str) -> Option<String> {\n\n use std::fs::File;\n\n use std::io::prelude::*;\n\n use std::io::BufReader;\n\n\n\n let symbols = File::open(\"/proc/kallsyms\");\n\n if symbols.is_err() {\n\n return None;\n\n }\n\n\n\n ...
Rust
codegen/src/ext/vt.rs
buty4649/vte
ea940fcb74abce67b927788e4f9f64fc63073d37
use std::fmt; use syntex::Registry; use syntex_syntax::ast::{self, Arm, Expr, ExprKind, LitKind, Pat, PatKind}; use syntex_syntax::codemap::Span; use syntex_syntax::ext::base::{DummyResult, ExtCtxt, MacEager, MacResult}; use syntex_syntax::ext::build::AstBuilder; use syntex_syntax::parse::parser::Parser; use syntex_syntax::parse::token::{DelimToken, Token}; use syntex_syntax::parse::PResult; use syntex_syntax::ptr::P; use syntex_syntax::tokenstream::TokenTree; #[path = "../../../src/definitions.rs"] mod definitions; use self::definitions::{Action, State}; pub fn register(registry: &mut Registry) { registry.add_macro("vt_state_table", expand_state_table); } fn state_from_str<S>(s: &S) -> Result<State, ()> where S: AsRef<str>, { Ok(match s.as_ref() { "State::Anywhere" => State::Anywhere, "State::CsiEntry" => State::CsiEntry, "State::CsiIgnore" => State::CsiIgnore, "State::CsiIntermediate" => State::CsiIntermediate, "State::CsiParam" => State::CsiParam, "State::DcsEntry" => State::DcsEntry, "State::DcsIgnore" => State::DcsIgnore, "State::DcsIntermediate" => State::DcsIntermediate, "State::DcsParam" => State::DcsParam, "State::DcsPassthrough" => State::DcsPassthrough, "State::Escape" => State::Escape, "State::EscapeIntermediate" => State::EscapeIntermediate, "State::Ground" => State::Ground, "State::OscString" => State::OscString, "State::SosPmApcString" => State::SosPmApcString, "State::Utf8" => State::Utf8, _ => return Err(()), }) } fn action_from_str<S>(s: &S) -> Result<Action, ()> where S: AsRef<str>, { Ok(match s.as_ref() { "Action::None" => Action::None, "Action::Clear" => Action::Clear, "Action::Collect" => Action::Collect, "Action::CsiDispatch" => Action::CsiDispatch, "Action::EscDispatch" => Action::EscDispatch, "Action::Execute" => Action::Execute, "Action::Hook" => Action::Hook, "Action::Ignore" => Action::Ignore, "Action::OscEnd" => Action::OscEnd, "Action::OscPut" => Action::OscPut, "Action::OscStart" => Action::OscStart, "Action::Param" => Action::Param, "Action::Print" => Action::Print, "Action::Put" => Action::Put, "Action::Unhook" => Action::Unhook, "Action::BeginUtf8" => Action::BeginUtf8, _ => return Err(()), }) } fn parse_table_input_mappings<'a>(parser: &mut Parser<'a>) -> PResult<'a, Vec<Arm>> { parser.expect(&Token::OpenDelim(DelimToken::Brace))?; let mut arms: Vec<Arm> = Vec::new(); while parser.token != Token::CloseDelim(DelimToken::Brace) { match parser.parse_arm() { Ok(arm) => arms.push(arm), Err(e) => { return Err(e); }, } } parser.bump(); Ok(arms) } #[derive(Debug)] struct TableDefinitionExprs { state_expr: P<Expr>, mapping_arms: Vec<Arm>, } fn state_from_expr(expr: P<Expr>, cx: &mut ExtCtxt) -> Result<State, ()> { let s = match expr.node { ExprKind::Path(ref _qself, ref path) => path.to_string(), _ => { cx.span_err(expr.span, "expected State"); return Err(()); }, }; state_from_str(&s).map_err(|_| { cx.span_err(expr.span, "expected State"); }) } fn u8_lit_from_expr(expr: &Expr, cx: &mut ExtCtxt) -> Result<u8, ()> { static MSG: &str = "expected u8 int literal"; match expr.node { ExprKind::Lit(ref lit) => match lit.node { LitKind::Int(val, _) => Ok(val as u8), _ => { cx.span_err(lit.span, MSG); Err(()) }, }, _ => { cx.span_err(expr.span, MSG); Err(()) }, } } fn input_mapping_from_arm(arm: Arm, cx: &mut ExtCtxt) -> Result<InputMapping, ()> { let Arm { pats, body, .. } = arm; let input = InputDefinition::from_pat(&pats[0], cx)?; let transition = Transition::from_expr(&body, cx)?; Ok(InputMapping { input, transition }) } #[derive(Copy, Clone)] enum Transition { State(State), Action(Action), StateAction(State, Action), } impl fmt::Debug for Transition { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Transition::State(state) => write!(f, "State({:?})", state)?, Transition::Action(action) => write!(f, "Action({:?})", action)?, Transition::StateAction(state, action) => { write!(f, "StateAction({:?}, {:?})", state, action)?; }, } write!(f, " -> {:?}", self.pack_u8()) } } impl Transition { fn pack_u8(self) -> u8 { match self { Transition::State(state) => state as u8, Transition::Action(action) => (action as u8) << 4, Transition::StateAction(state, action) => ((action as u8) << 4) | (state as u8), } } } impl Transition { fn from_expr(expr: &Expr, cx: &mut ExtCtxt) -> Result<Transition, ()> { match expr.node { ExprKind::Tup(ref tup_exprs) => { let mut action = None; let mut state = None; for tup_expr in tup_exprs { if let ExprKind::Path(_, ref path) = tup_expr.node { let path_str = path.to_string(); if path_str.starts_with('A') { action = Some(action_from_str(&path_str).map_err(|_| { cx.span_err(expr.span, "invalid action"); })?); } else { state = Some(state_from_str(&path_str).map_err(|_| { cx.span_err(expr.span, "invalid state"); })?); } } } match (action, state) { (Some(action), Some(state)) => Ok(Transition::StateAction(state, action)), (None, Some(state)) => Ok(Transition::State(state)), (Some(action), None) => Ok(Transition::Action(action)), _ => { cx.span_err(expr.span, "expected Action and/or State"); Err(()) }, } }, ExprKind::Path(_, ref path) => { let path_str = path.to_string(); if path_str.starts_with('A') { let action = action_from_str(&path_str).map_err(|_| { cx.span_err(expr.span, "invalid action"); })?; Ok(Transition::Action(action)) } else { let state = state_from_str(&path_str).map_err(|_| { cx.span_err(expr.span, "invalid state"); })?; Ok(Transition::State(state)) } }, _ => { cx.span_err(expr.span, "expected Action and/or State"); Err(()) }, } } } #[derive(Debug)] enum InputDefinition { Specific(u8), Range { start: u8, end: u8 }, } impl InputDefinition { fn from_pat(pat: &Pat, cx: &mut ExtCtxt) -> Result<InputDefinition, ()> { Ok(match pat.node { PatKind::Lit(ref lit_expr) => { InputDefinition::Specific(u8_lit_from_expr(&lit_expr, cx)?) }, PatKind::Range(ref start_expr, ref end_expr) => InputDefinition::Range { start: u8_lit_from_expr(start_expr, cx)?, end: u8_lit_from_expr(end_expr, cx)?, }, _ => { cx.span_err(pat.span, "expected literal or range expression"); return Err(()); }, }) } } #[derive(Debug)] struct InputMapping { input: InputDefinition, transition: Transition, } #[derive(Debug)] struct TableDefinition { state: State, mappings: Vec<InputMapping>, } fn parse_raw_definitions( definitions: Vec<TableDefinitionExprs>, cx: &mut ExtCtxt, ) -> Result<Vec<TableDefinition>, ()> { let mut out = Vec::new(); for raw in definitions { let TableDefinitionExprs { state_expr, mapping_arms } = raw; let state = state_from_expr(state_expr, cx)?; let mut mappings = Vec::new(); for arm in mapping_arms { mappings.push(input_mapping_from_arm(arm, cx)?); } out.push(TableDefinition { state, mappings }) } Ok(out) } fn parse_table_definition<'a>(parser: &mut Parser<'a>) -> PResult<'a, TableDefinitionExprs> { let state_expr = parser.parse_expr()?; parser.expect(&Token::FatArrow)?; let mappings = parse_table_input_mappings(parser)?; Ok(TableDefinitionExprs { state_expr, mapping_arms: mappings }) } fn parse_table_definition_list<'a>( parser: &mut Parser<'a>, ) -> PResult<'a, Vec<TableDefinitionExprs>> { let mut definitions = Vec::new(); while parser.token != Token::Eof { definitions.push(parse_table_definition(parser)?); parser.eat(&Token::Comma); } Ok(definitions) } fn build_state_tables<T>(defs: T) -> [[u8; 256]; 16] where T: AsRef<[TableDefinition]>, { let mut result = [[0u8; 256]; 16]; for def in defs.as_ref() { let state = def.state; let state = state as u8; let transitions = &mut result[state as usize]; for mapping in &def.mappings { let trans = mapping.transition.pack_u8(); match mapping.input { InputDefinition::Specific(idx) => { transitions[idx as usize] = trans; }, InputDefinition::Range { start, end } => { for idx in start..end { transitions[idx as usize] = trans; } transitions[end as usize] = trans; }, } } } result } fn build_table_ast(cx: &mut ExtCtxt, sp: Span, table: [[u8; 256]; 16]) -> P<ast::Expr> { let table = table .iter() .map(|list| { let exprs = list.iter().map(|num| cx.expr_u8(sp, *num)).collect(); cx.expr_vec(sp, exprs) }) .collect(); cx.expr_vec(sp, table) } fn expand_state_table<'cx>( cx: &'cx mut ExtCtxt, sp: Span, args: &[TokenTree], ) -> Box<dyn MacResult + 'cx> { macro_rules! ptry { ($pres:expr) => { match $pres { Ok(val) => val, Err(mut err) => { err.emit(); return DummyResult::any(sp); }, } }; } let mut parser: Parser = cx.new_parser_from_tts(args); let definitions = ptry!(parse_table_definition_list(&mut parser)); let definitions = match parse_raw_definitions(definitions, cx) { Ok(definitions) => definitions, Err(_) => return DummyResult::any(sp), }; let table = build_state_tables(&definitions); let ast = build_table_ast(cx, sp, table); MacEager::expr(ast) } #[cfg(test)] mod tests { use super::definitions::{Action, State}; use super::Transition; #[test] fn pack_u8() { let transition = Transition::StateAction(State::CsiParam, Action::Collect); assert_eq!(transition.pack_u8(), 0x24); } }
use std::fmt; use syntex::Registry; use syntex_syntax::ast::{self, Arm, Expr, ExprKind, LitKind, Pat, PatKind}; use syntex_syntax::codemap::Span; use syntex_syntax::ext::base::{DummyResult, ExtCtxt, MacEager, MacResult}; use syntex_syntax::ext::build::AstBuilder; use syntex_syntax::parse::parser::Parser; use syntex_syntax::parse::token::{DelimToken, Token}; use syntex_syntax::parse::PResult; use syntex_syntax::ptr::P; use syntex_syntax::tokenstream::TokenTree; #[path = "../../../src/definitions.rs"] mod definitions; use self::definitions::{Action, State}; pub fn register(registry: &mut Registry) { registry.add_macro("vt_state_table", expand_state_table); } fn state_from_str<S>(s: &S) -> Result<State, ()> where S: AsRef<str>, { Ok(match s.as_ref() { "State::Anywhere" => State::Anywhere, "State::CsiEntry" => State::CsiEntry, "State::CsiIgnore" => State::CsiIgnore, "State::CsiIntermediate" => State::CsiIntermediate, "State::CsiParam" => State::CsiParam, "State::DcsEntry" => State::DcsEntry, "State::DcsIgnore" => State::DcsIgnore, "State::DcsIntermediate" => State::DcsIntermediate, "State::DcsParam" => State::DcsParam, "State::DcsPassthrough" => State::DcsPassthrough, "State::Escape" => State::Escape, "State::EscapeIntermediate" => State::EscapeIntermediate, "State::Ground" => State::Ground, "State::OscString" => State::OscString, "State::SosPmApcString" => State::SosPmApcString, "State::Utf8" => State::Utf8, _ => return Err(()), }) } fn action_from_str<S>(s: &S) -> Result<Action, ()> where S: AsRef<str>, { Ok(match s.as_ref() { "Action::None" => Action::None, "Action::Clear" => Action::Clear, "Action::Collect" => Action::Collect, "Action::CsiDispatch" => Action::CsiDispatch, "Action::EscDispatch" => Action::EscDispatch, "Action::Execute" => Action::Execute, "Action::Hook" => Action::Hook, "Action::Ignore" => Action::Ignore, "Action::OscEnd" => Action::OscEnd, "Action::OscPut" => Action::OscPut, "Action::OscStart" => Action::OscStart, "Action::Param" => Action::Param, "Action::Print" => Action::Print, "Action::Put" => Action::Put, "Action::Unhook" => Action::Unhook, "Action::BeginUtf8" => Action::BeginUtf8, _ => return Err(()), }) } fn parse_table_input_mappings<'a>(parser: &mut Parser<'a>) -> PResult<'a, Vec<Arm>> { parser.expect(&Token::OpenDelim(DelimToken::Brace))?; let mut arms: Vec<Arm> = Vec::new(); while parser.token != Token::CloseDelim(DelimToken::Brace) { match parser.parse_arm() { Ok(arm) => arms.push(arm), Err(e) => { return Err(e); }, } } parser.bump(); Ok(arms) } #[derive(Debug)] struct TableDefinitionExprs { state_expr: P<Expr>, mapping_arms: Vec<Arm>, } fn state_from_expr(expr: P<Expr>, cx: &mut ExtCtxt) -> Result<State, ()> { let s = match expr.node { ExprKind::Path(ref _qself, ref path) => path.to_string(), _ => { cx.span_err(expr.span, "expected State"); return Err(()); }, }; state_from_str(&s).map_err(|_| { cx.span_err(expr.span, "expected State"); }) } fn u8_lit_from_expr(expr: &Expr, cx: &mut ExtCtxt) -> Result<u8, ()> { static MSG: &str = "expected u8 int literal"; match expr.node { ExprKind::Lit(ref lit) => match lit.node { LitKind::Int(val, _) => Ok(val as u8), _ => { cx.span_err(lit.span, MSG); Err(()) }, }, _ => { cx.span_err(expr.span, MSG); Err(()) }, } } fn input_mapping_from_arm(arm: Arm, cx: &mut ExtCtxt) -> Result<InputMapping, ()> { let Arm { pats, body, .. } = arm; let input = InputDefinition::from_pat(&pats[0], cx)?; let transition = Transition::from_expr(&body, cx)?; Ok(InputMapping { input, transition }) } #[derive(Copy, Clone)] enum Transition { State(State), Action(Action), StateAction(State, Action), } impl fmt::Debug for Transition { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Transition::State(state) => write!(f, "State({:?})", state)?, Transition::Action(action) => write!(f, "Action({:?})", action)?, Transition::StateAction(state, action) => { write!(f, "StateAction({:?}, {:?})", state, action)?; }, } write!(f, " -> {:?}", self.pack_u8()) } } impl Transition { fn pack_u8(self) -> u8 { match self { Transition::State(state) => state as u8, Transition::Action(action) => (action as u8) << 4, Transition::StateAction(state, action) => ((action as u8) << 4) | (state as u8), } } } impl Transition { fn from_expr(expr: &Expr, cx: &mut ExtCtxt) -> Result<Transition, ()> { match expr.node { ExprKind::Tup(ref tup_exprs) => { let mut action = None; let mut state = None; for tup_expr in tup_exprs { if let ExprKind::Path(_, ref path) = tup_expr.node { let path_str = path.to_string(); if path_str.starts_with('A') { action =
; } else { state = Some(state_from_str(&path_str).map_err(|_| { cx.span_err(expr.span, "invalid state"); })?); } } } match (action, state) { (Some(action), Some(state)) => Ok(Transition::StateAction(state, action)), (None, Some(state)) => Ok(Transition::State(state)), (Some(action), None) => Ok(Transition::Action(action)), _ => { cx.span_err(expr.span, "expected Action and/or State"); Err(()) }, } }, ExprKind::Path(_, ref path) => { let path_str = path.to_string(); if path_str.starts_with('A') { let action = action_from_str(&path_str).map_err(|_| { cx.span_err(expr.span, "invalid action"); })?; Ok(Transition::Action(action)) } else { let state = state_from_str(&path_str).map_err(|_| { cx.span_err(expr.span, "invalid state"); })?; Ok(Transition::State(state)) } }, _ => { cx.span_err(expr.span, "expected Action and/or State"); Err(()) }, } } } #[derive(Debug)] enum InputDefinition { Specific(u8), Range { start: u8, end: u8 }, } impl InputDefinition { fn from_pat(pat: &Pat, cx: &mut ExtCtxt) -> Result<InputDefinition, ()> { Ok(match pat.node { PatKind::Lit(ref lit_expr) => { InputDefinition::Specific(u8_lit_from_expr(&lit_expr, cx)?) }, PatKind::Range(ref start_expr, ref end_expr) => InputDefinition::Range { start: u8_lit_from_expr(start_expr, cx)?, end: u8_lit_from_expr(end_expr, cx)?, }, _ => { cx.span_err(pat.span, "expected literal or range expression"); return Err(()); }, }) } } #[derive(Debug)] struct InputMapping { input: InputDefinition, transition: Transition, } #[derive(Debug)] struct TableDefinition { state: State, mappings: Vec<InputMapping>, } fn parse_raw_definitions( definitions: Vec<TableDefinitionExprs>, cx: &mut ExtCtxt, ) -> Result<Vec<TableDefinition>, ()> { let mut out = Vec::new(); for raw in definitions { let TableDefinitionExprs { state_expr, mapping_arms } = raw; let state = state_from_expr(state_expr, cx)?; let mut mappings = Vec::new(); for arm in mapping_arms { mappings.push(input_mapping_from_arm(arm, cx)?); } out.push(TableDefinition { state, mappings }) } Ok(out) } fn parse_table_definition<'a>(parser: &mut Parser<'a>) -> PResult<'a, TableDefinitionExprs> { let state_expr = parser.parse_expr()?; parser.expect(&Token::FatArrow)?; let mappings = parse_table_input_mappings(parser)?; Ok(TableDefinitionExprs { state_expr, mapping_arms: mappings }) } fn parse_table_definition_list<'a>( parser: &mut Parser<'a>, ) -> PResult<'a, Vec<TableDefinitionExprs>> { let mut definitions = Vec::new(); while parser.token != Token::Eof { definitions.push(parse_table_definition(parser)?); parser.eat(&Token::Comma); } Ok(definitions) } fn build_state_tables<T>(defs: T) -> [[u8; 256]; 16] where T: AsRef<[TableDefinition]>, { let mut result = [[0u8; 256]; 16]; for def in defs.as_ref() { let state = def.state; let state = state as u8; let transitions = &mut result[state as usize]; for mapping in &def.mappings { let trans = mapping.transition.pack_u8(); match mapping.input { InputDefinition::Specific(idx) => { transitions[idx as usize] = trans; }, InputDefinition::Range { start, end } => { for idx in start..end { transitions[idx as usize] = trans; } transitions[end as usize] = trans; }, } } } result } fn build_table_ast(cx: &mut ExtCtxt, sp: Span, table: [[u8; 256]; 16]) -> P<ast::Expr> { let table = table .iter() .map(|list| { let exprs = list.iter().map(|num| cx.expr_u8(sp, *num)).collect(); cx.expr_vec(sp, exprs) }) .collect(); cx.expr_vec(sp, table) } fn expand_state_table<'cx>( cx: &'cx mut ExtCtxt, sp: Span, args: &[TokenTree], ) -> Box<dyn MacResult + 'cx> { macro_rules! ptry { ($pres:expr) => { match $pres { Ok(val) => val, Err(mut err) => { err.emit(); return DummyResult::any(sp); }, } }; } let mut parser: Parser = cx.new_parser_from_tts(args); let definitions = ptry!(parse_table_definition_list(&mut parser)); let definitions = match parse_raw_definitions(definitions, cx) { Ok(definitions) => definitions, Err(_) => return DummyResult::any(sp), }; let table = build_state_tables(&definitions); let ast = build_table_ast(cx, sp, table); MacEager::expr(ast) } #[cfg(test)] mod tests { use super::definitions::{Action, State}; use super::Transition; #[test] fn pack_u8() { let transition = Transition::StateAction(State::CsiParam, Action::Collect); assert_eq!(transition.pack_u8(), 0x24); } }
Some(action_from_str(&path_str).map_err(|_| { cx.span_err(expr.span, "invalid action"); })?)
call_expression
[ { "content": "fn u8_lit_from_expr(expr: &Expr, cx: &mut ExtCtxt) -> Result<u8, ()> {\n\n static MSG: &str = \"expected u8 int literal\";\n\n\n\n match expr.node {\n\n ExprKind::Lit(ref lit) => match lit.node {\n\n LitKind::Int(val, _) => Ok(val as u8),\n\n _ => {\n\n ...
Rust
third_party/rust_crates/vendor/toml_edit/src/parser/strings.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use crate::decor::InternalString; use crate::parser::errors::CustomError; use crate::parser::trivia::{newline, ws, ws_newlines}; use combine::error::{Commit, Info}; use combine::parser::char::char; use combine::parser::range::{range, take, take_while}; use combine::stream::RangeStream; use combine::*; use std::char; parse!(string() -> InternalString, { choice(( ml_basic_string(), basic_string(), ml_literal_string(), literal_string().map(|s: &'a str| s.into()), )) }); #[inline] fn is_basic_unescaped(c: char) -> bool { matches!(c, '\u{20}'..='\u{21}' | '\u{23}'..='\u{5B}' | '\u{5D}'..='\u{10FFFF}') } #[inline] fn is_escape_char(c: char) -> bool { matches!( c, '\\' | '"' | 'b' | '/' | 'f' | 'n' | 'r' | 't' | 'u' | 'U' ) } parse!(escape() -> char, { satisfy(is_escape_char) .message("While parsing escape sequence") .then(|c| { parser(move |input| { match c { 'b' => Ok(('\u{8}', Commit::Peek(()))), 'f' => Ok(('\u{c}', Commit::Peek(()))), 'n' => Ok(('\n', Commit::Peek(()))), 'r' => Ok(('\r', Commit::Peek(()))), 't' => Ok(('\t', Commit::Peek(()))), 'u' => hexescape(4).parse_stream(input).into_result(), 'U' => hexescape(8).parse_stream(input).into_result(), _ => Ok((c, Commit::Peek(()))), } }) }) }); parse!(hexescape(n: usize) -> char, { take(*n) .and_then(|s| u32::from_str_radix(s, 16)) .and_then(|h| char::from_u32(h).ok_or(CustomError::InvalidHexEscape(h))) }); const ESCAPE: char = '\\'; parse!(basic_char() -> char, { satisfy(|c| is_basic_unescaped(c) || c == ESCAPE) .then(|c| parser(move |input| { match c { ESCAPE => escape().parse_stream(input).into_result(), _ => Ok((c, Commit::Peek(()))), } })) }); const QUOTATION_MARK: char = '"'; parse!(basic_string() -> InternalString, { between(char(QUOTATION_MARK), char(QUOTATION_MARK), many(basic_char())) .message("While parsing a Basic String") }); #[inline] fn is_ml_basic_unescaped(c: char) -> bool { matches!(c, '\u{20}'..='\u{5B}' | '\u{5D}'..='\u{10FFFF}') } const ML_BASIC_STRING_DELIM: &str = "\"\"\""; parse!(ml_basic_char() -> char, { satisfy(|c| is_ml_basic_unescaped(c) || c == ESCAPE) .then(|c| parser(move |input| { match c { ESCAPE => escape().parse_stream(input).into_result(), _ => Ok((c, Commit::Peek(()))), } })) }); parse!(try_eat_escaped_newline() -> (), { skip_many(attempt(( char(ESCAPE), ws(), ws_newlines(), ))) }); parse!(ml_basic_body() -> InternalString, { optional(newline()) .skip(try_eat_escaped_newline()) .with( many( not_followed_by(range(ML_BASIC_STRING_DELIM).map(Info::Range)) .with( choice(( newline(), ml_basic_char(), )) ) .skip(try_eat_escaped_newline()) ) ) }); parse!(ml_basic_string() -> InternalString, { between(range(ML_BASIC_STRING_DELIM), range(ML_BASIC_STRING_DELIM), ml_basic_body()) .message("While parsing a Multiline Basic String") }); const APOSTROPHE: char = '\''; #[inline] fn is_literal_char(c: char) -> bool { matches!(c, '\u{09}' | '\u{20}'..='\u{26}' | '\u{28}'..='\u{10FFFF}') } parse!(literal_string() -> &'a str, { between(char(APOSTROPHE), char(APOSTROPHE), take_while(is_literal_char)) .message("While parsing a Literal String") }); const ML_LITERAL_STRING_DELIM: &str = "'''"; #[inline] fn is_ml_literal_char(c: char) -> bool { matches!(c, '\u{09}' | '\u{20}'..='\u{10FFFF}') } parse!(ml_literal_body() -> InternalString, { optional(newline()) .with( many( not_followed_by(range(ML_LITERAL_STRING_DELIM).map(Info::Range)) .with( choice(( newline(), satisfy(is_ml_literal_char), )) ) ) ) }); parse!(ml_literal_string() -> InternalString, { between(range(ML_LITERAL_STRING_DELIM), range(ML_LITERAL_STRING_DELIM), ml_literal_body()) .message("While parsing a Multiline Literal String") });
use crate::decor::InternalString; use crate::parser::errors::CustomError; use crate::parser::trivia::{newline, ws, ws_newlines}; use combine::error::{Commit, Info}; use combine::parser::char::char; use combine::parser::range::{range, take, take_while}; use combine::stream::RangeStream; use combine::*; use std::char; parse!(string() -> InternalString, { choice(( ml_basic_string(), basic_string(), ml_literal_string(), literal_string().map(|s: &'a str| s.into()), )) }); #[inline] fn is_basic_unescaped(c: char) -> bool { matches!(c, '\u{20}'..='\u{21}' | '\u{23}'..='\u{5B}' | '\u{5D}'..='\u{10FFFF}') } #[inline] fn is_escape_char(c: char) -> bool { matches!( c, '\\' | '"' | 'b' | '/' | 'f' | 'n' | 'r' | 't' | 'u' | 'U' ) } parse!(escape() -> char, { satisfy(is_escape_char) .message("While parsing escape seq
ml_literal_body()) .message("While parsing a Multiline Literal String") });
uence") .then(|c| { parser(move |input| { match c { 'b' => Ok(('\u{8}', Commit::Peek(()))), 'f' => Ok(('\u{c}', Commit::Peek(()))), 'n' => Ok(('\n', Commit::Peek(()))), 'r' => Ok(('\r', Commit::Peek(()))), 't' => Ok(('\t', Commit::Peek(()))), 'u' => hexescape(4).parse_stream(input).into_result(), 'U' => hexescape(8).parse_stream(input).into_result(), _ => Ok((c, Commit::Peek(()))), } }) }) }); parse!(hexescape(n: usize) -> char, { take(*n) .and_then(|s| u32::from_str_radix(s, 16)) .and_then(|h| char::from_u32(h).ok_or(CustomError::InvalidHexEscape(h))) }); const ESCAPE: char = '\\'; parse!(basic_char() -> char, { satisfy(|c| is_basic_unescaped(c) || c == ESCAPE) .then(|c| parser(move |input| { match c { ESCAPE => escape().parse_stream(input).into_result(), _ => Ok((c, Commit::Peek(()))), } })) }); const QUOTATION_MARK: char = '"'; parse!(basic_string() -> InternalString, { between(char(QUOTATION_MARK), char(QUOTATION_MARK), many(basic_char())) .message("While parsing a Basic String") }); #[inline] fn is_ml_basic_unescaped(c: char) -> bool { matches!(c, '\u{20}'..='\u{5B}' | '\u{5D}'..='\u{10FFFF}') } const ML_BASIC_STRING_DELIM: &str = "\"\"\""; parse!(ml_basic_char() -> char, { satisfy(|c| is_ml_basic_unescaped(c) || c == ESCAPE) .then(|c| parser(move |input| { match c { ESCAPE => escape().parse_stream(input).into_result(), _ => Ok((c, Commit::Peek(()))), } })) }); parse!(try_eat_escaped_newline() -> (), { skip_many(attempt(( char(ESCAPE), ws(), ws_newlines(), ))) }); parse!(ml_basic_body() -> InternalString, { optional(newline()) .skip(try_eat_escaped_newline()) .with( many( not_followed_by(range(ML_BASIC_STRING_DELIM).map(Info::Range)) .with( choice(( newline(), ml_basic_char(), )) ) .skip(try_eat_escaped_newline()) ) ) }); parse!(ml_basic_string() -> InternalString, { between(range(ML_BASIC_STRING_DELIM), range(ML_BASIC_STRING_DELIM), ml_basic_body()) .message("While parsing a Multiline Basic String") }); const APOSTROPHE: char = '\''; #[inline] fn is_literal_char(c: char) -> bool { matches!(c, '\u{09}' | '\u{20}'..='\u{26}' | '\u{28}'..='\u{10FFFF}') } parse!(literal_string() -> &'a str, { between(char(APOSTROPHE), char(APOSTROPHE), take_while(is_literal_char)) .message("While parsing a Literal String") }); const ML_LITERAL_STRING_DELIM: &str = "'''"; #[inline] fn is_ml_literal_char(c: char) -> bool { matches!(c, '\u{09}' | '\u{20}'..='\u{10FFFF}') } parse!(ml_literal_body() -> InternalString, { optional(newline()) .with( many( not_followed_by(range(ML_LITERAL_STRING_DELIM).map(Info::Range)) .with( choice(( newline(), satisfy(is_ml_literal_char), )) ) ) ) }); parse!(ml_literal_string() -> InternalString, { between(range(ML_LITERAL_STRING_DELIM), range(ML_LITERAL_STRING_DELIM),
random
[]
Rust
src/runtime/opcode/args.rs
Miyakowww/aoi
3cfbe4ef2ada58b10751ee4a0dd2a041c4cd4d23
use std::fmt::Display; use crate::AoStatus; use crate::AoType; use crate::AoVM; #[derive(Debug, PartialEq, Clone)] pub enum AoArg { PC, DP, MP, DSB, DST, CA, DS, MEM, Imm(AoType), } impl AoArg { pub fn get_value(&self, vm: &AoVM) -> AoType { match self { AoArg::PC => AoType::AoPtr(vm.pc), AoArg::DP => AoType::AoPtr(vm.dp), AoArg::MP => AoType::AoPtr(vm.mp), AoArg::DSB => AoType::AoPtr(vm.dsb as u32), AoArg::DST => AoType::AoPtr(vm.ds.len() as u32), AoArg::CA => vm.ca.clone(), AoArg::DS => vm.ds[vm.dp as usize].clone(), AoArg::MEM => vm.mem.get(vm.mp), AoArg::Imm(value) => value.clone(), } } pub fn set_value(&self, vm: &mut AoVM, value: AoType) -> AoStatus { match self { AoArg::PC => match value { AoType::AoPtr(p) => { vm.pc = p; AoStatus::Ok } _ => { AoStatus::SetValueInvalidType("cannot set PC to non-pointer value".to_string()) } }, AoArg::DP => match value { AoType::AoPtr(p) => { vm.dp = p; AoStatus::Ok } _ => { AoStatus::SetValueInvalidType("cannot set DP to non-pointer value".to_string()) } }, AoArg::MP => match value { AoType::AoPtr(p) => { vm.mp = p; AoStatus::Ok } _ => { AoStatus::SetValueInvalidType("cannot set MP to non-pointer value".to_string()) } }, AoArg::DSB => match value { AoType::AoPtr(p) => { vm.dsb = p; AoStatus::Ok } _ => AoStatus::SetValueInvalidType(format!("cannot set DSB to {}", value)), }, AoArg::DST => AoStatus::SetValueInvalidTarget("cannot set DST".to_string()), AoArg::CA => { vm.ca = value; AoStatus::Ok } AoArg::DS => { vm.ds[vm.dp as usize] = value; AoStatus::Ok } AoArg::MEM => { vm.mem.set(vm.mp, value); AoStatus::Ok } AoArg::Imm(_) => { AoStatus::SetValueInvalidTarget("cannot set immediate value".to_string()) } } } } impl Display for AoArg { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { AoArg::PC => write!(f, "pc"), AoArg::DP => write!(f, "dp"), AoArg::MP => write!(f, "mp"), AoArg::DSB => write!(f, "dsb"), AoArg::DST => write!(f, "dst"), AoArg::CA => write!(f, "ca"), AoArg::DS => write!(f, "ds"), AoArg::MEM => write!(f, "mem"), AoArg::Imm(v) => write!(f, "{}", v), } } } macro_rules! impl_from { ( $at:ident, &str ) => { impl From<&str> for AoArg { fn from(t: &str) -> AoArg { AoArg::Imm(AoType::$at(t.to_string())) } } }; ( $at:ident, $rt:ty ) => { impl From<$rt> for AoArg { fn from(t: $rt) -> AoArg { AoArg::Imm(AoType::$at(t)) } } }; } impl_from!(AoBool, bool); impl_from!(AoInt, i32); impl_from!(AoFloat, f32); impl_from!(AoPtr, u32); impl_from!(AoString, String); impl_from!(AoString, &str); #[allow(non_camel_case_types)] pub enum AoArgLowerCase { pc, dp, mp, dsb, dst, ca, ds, mem, imm(AoType), } impl AoArgLowerCase { pub fn to_aoarg(&self) -> AoArg { match self { AoArgLowerCase::pc => AoArg::PC, AoArgLowerCase::dp => AoArg::DP, AoArgLowerCase::mp => AoArg::MP, AoArgLowerCase::dsb => AoArg::DSB, AoArgLowerCase::dst => AoArg::DST, AoArgLowerCase::ca => AoArg::CA, AoArgLowerCase::ds => AoArg::DS, AoArgLowerCase::mem => AoArg::MEM, AoArgLowerCase::imm(v) => AoArg::Imm(v.clone()), } } }
use std::fmt::Display; use crate::AoStatus; use crate::AoType; use crate::AoVM; #[derive(Debug, PartialEq, Clone)] pub enum AoArg { PC, DP, MP, DSB, DST, CA, DS, MEM, Imm(AoType), } impl AoArg { pub fn get_value(&self, vm: &AoVM) -> AoType { match self { AoArg::PC => AoType::AoPtr(vm.pc), AoArg::DP => AoType::AoPtr(vm.dp), AoArg::MP => AoType::AoPtr(vm.mp), AoArg::DSB => AoType::AoPtr(vm.dsb as u32), AoArg::DST => AoType::AoPtr(vm.ds.len() as u32), AoArg::CA => vm.ca.clone(), AoArg::DS => vm.ds[vm.dp as usize].clone(), AoArg::MEM => vm.mem.get(vm.mp), AoArg::Imm(value) => value.clone(), } } pub fn set_value(&self, vm: &mut AoVM, value: AoType) -> AoStatus { match self { AoArg::PC => match value { AoType::AoPtr(p) => { vm.pc = p; AoStatus::Ok } _ => { AoStatus::SetValueInvalidType("cannot set PC to non-pointer value".to_string()) } }, AoArg::DP => match value { AoType::AoPtr(p) => { vm.dp = p; AoStatus::Ok } _ => { AoStatus::SetValueInvalidType("cannot set DP to non-pointer value".to_string()) } }, AoArg::MP => match value { AoType::AoPtr(p) => { vm.mp = p; AoStatus::Ok } _ => { AoStatus::SetValueInvalidType("cannot set MP to non-pointer value".to_string()) } }, AoArg::DSB => match value { AoType::AoPtr(p) => { vm.dsb = p; AoStatus::Ok } _ => AoStatus::SetValueInvalidType(format!("cannot set DSB to {}", value)), }, AoArg::DST => AoStatus::SetValueInvalidTarget("cannot set DST".to_string()), AoArg::CA => { vm.ca = value; AoStatus::Ok } AoArg::DS => { vm.ds[vm.dp as usize] = value; AoStatus::Ok } AoArg::MEM => { vm.mem.set(vm.mp, value); AoStatus::Ok } AoArg::Imm(_) => { AoStatus::SetValueInvalidTarget("cannot set immediate value".to_string()) } } } } impl Display for AoArg { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { AoArg::PC => write!(f, "pc"), AoArg::DP => write!(f, "dp"), AoArg::MP => write!(f, "mp"), AoArg::DSB => write!(f, "dsb"), AoArg::DST => write!(f, "dst"), AoArg::CA => write!(f, "ca"), AoArg::DS => write!(f, "ds"), AoArg::MEM => write!(f, "mem"), AoArg::Imm(v) => write!(f, "{}", v), } } } macro_rules! impl_from { ( $at:ident, &str ) => { impl From<&str> for AoArg { fn from(t: &str) -> AoArg { AoArg::Imm(AoType::$at(t.to_string())) } } }; ( $at:ident, $rt:ty ) => { impl From<$rt> for AoArg { fn from(t: $rt) -> AoArg { AoArg::Imm(AoType::$at(t)) } } }; } impl_from!(AoBool, bool); impl_from!(AoInt, i32); impl_from!(AoFloat, f32); impl_from!(AoPtr, u32); impl_from!(AoString, String); impl_from!(AoString, &str); #[allow(non_camel_case_types)] pub enum AoArgLowerCase { pc, dp, mp, dsb, dst, ca, ds, mem, imm(AoType), } impl AoArgLowerCase {
}
pub fn to_aoarg(&self) -> AoArg { match self { AoArgLowerCase::pc => AoArg::PC, AoArgLowerCase::dp => AoArg::DP, AoArgLowerCase::mp => AoArg::MP, AoArgLowerCase::dsb => AoArg::DSB, AoArgLowerCase::dst => AoArg::DST, AoArgLowerCase::ca => AoArg::CA, AoArgLowerCase::ds => AoArg::DS, AoArgLowerCase::mem => AoArg::MEM, AoArgLowerCase::imm(v) => AoArg::Imm(v.clone()), } }
function_block-full_function
[ { "content": "fn clone_vm_status(vm: &AoVM) -> AoVM {\n\n let mut new_vm = AoVM::new(|_, _| None);\n\n new_vm.pc = vm.pc;\n\n new_vm.ca = vm.ca.clone();\n\n new_vm.dp = vm.dp;\n\n new_vm.dsb = vm.dsb;\n\n new_vm.ds = vm.ds.clone();\n\n new_vm\n\n}\n", "file_path": "examples/single_step....
Rust
src/lib.rs
SOF3/minihtml
4294517978e446b4971cd8327ac97a12fb728b1f
use std::fmt; pub type Result<T = (), E = fmt::Error> = std::result::Result<T, E>; pub trait ToHtmlNode { fn fmt(&self, f: &mut fmt::Formatter) -> Result; } pub trait ToWholeHtmlAttr { fn fmt(&self, name: NoSpecial<'_>, f: &mut fmt::Formatter) -> Result; } pub trait ToHtmlAttr { fn fmt(&self, f: &mut fmt::Formatter) -> Result; } impl<T: ToHtmlAttr + ?Sized> ToWholeHtmlAttr for T { #[inline] fn fmt(&self, name: NoSpecial<'_>, f: &mut fmt::Formatter) -> Result { write!(f, " {}=\"", name.0)?; ToHtmlAttr::fmt(self, f)?; write!(f, "\"")?; Ok(()) } } #[derive(Debug, Clone, Copy)] pub struct NoSpecial<'t>(pub &'t str); impl<'t> NoSpecial<'t> { #[inline] pub fn debug_checked(value: &'t str) -> Self { debug_assert!( !has_special_chars(value), "Value passed to NoSpecial::debug_checked() contains speicla characters: {:?}", value ); Self(value) } } fn has_special_chars(s: &str) -> bool { s.contains(|c| match c { '&' | '<' | '>' | '\'' | '"' => true, _ => false, }) } impl<'t> ToHtmlNode for NoSpecial<'t> { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> Result { write!(f, "{}", self.0) } } impl<'t> ToHtmlAttr for NoSpecial<'t> { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> Result { write!(f, "{}", self.0) } } struct Escaped<'t>(&'t str); impl<'t> fmt::Display for Escaped<'t> { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> Result { for char in self.0.chars() { let escape = match char { '&' => "&amp;", '<' => "&lt;", '>' => "&gt;", '\'' => "&apos;", '"' => "&quot;", _ => { write!(f, "{}", char)?; continue; } }; write!(f, "{}", escape)?; } Ok(()) } } mod primitives; #[proc_macro_hack::proc_macro_hack] pub use minihtml_codegen::html; #[doc(hidden)] pub struct HtmlString<T: ToHtmlNode>(pub T); impl<T: ToHtmlNode> fmt::Display for HtmlString<T> { fn fmt(&self, f: &mut fmt::Formatter) -> Result { ToHtmlNode::fmt(&self.0, f) } } #[doc(hidden)] pub struct Html<F>(pub F) where F: Fn(&mut ::std::fmt::Formatter) -> fmt::Result; impl<F> ToHtmlNode for Html<F> where F: Fn(&mut ::std::fmt::Formatter) -> fmt::Result, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (self.0)(f) } } #[macro_export] macro_rules! html_string { ($($tt:tt)*) => {{ let node = $crate::html!($($tt)*); format!("{}", $crate::HtmlString(node)) }} } #[doc(hidden)] pub mod hc;
use std::fmt; pub type Result<T = (), E = fmt::Error> = std::result::Result<T, E>; pub trait ToHtmlNode { fn fmt(&self, f: &mut fmt::Formatter) -> Result; } pub trait ToWholeHtmlAttr { fn fmt(&self, name: NoSpecial<'_>, f: &mut fmt::Formatter) -> Result; } pub trait ToHtmlAttr { fn fmt(&self, f: &mut fmt::Formatter) -> Result; } impl<T: ToHtmlAttr + ?Sized> ToWholeHtmlAttr for T { #[inline] fn fmt(&se
} #[derive(Debug, Clone, Copy)] pub struct NoSpecial<'t>(pub &'t str); impl<'t> NoSpecial<'t> { #[inline] pub fn debug_checked(value: &'t str) -> Self { debug_assert!( !has_special_chars(value), "Value passed to NoSpecial::debug_checked() contains speicla characters: {:?}", value ); Self(value) } } fn has_special_chars(s: &str) -> bool { s.contains(|c| match c { '&' | '<' | '>' | '\'' | '"' => true, _ => false, }) } impl<'t> ToHtmlNode for NoSpecial<'t> { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> Result { write!(f, "{}", self.0) } } impl<'t> ToHtmlAttr for NoSpecial<'t> { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> Result { write!(f, "{}", self.0) } } struct Escaped<'t>(&'t str); impl<'t> fmt::Display for Escaped<'t> { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> Result { for char in self.0.chars() { let escape = match char { '&' => "&amp;", '<' => "&lt;", '>' => "&gt;", '\'' => "&apos;", '"' => "&quot;", _ => { write!(f, "{}", char)?; continue; } }; write!(f, "{}", escape)?; } Ok(()) } } mod primitives; #[proc_macro_hack::proc_macro_hack] pub use minihtml_codegen::html; #[doc(hidden)] pub struct HtmlString<T: ToHtmlNode>(pub T); impl<T: ToHtmlNode> fmt::Display for HtmlString<T> { fn fmt(&self, f: &mut fmt::Formatter) -> Result { ToHtmlNode::fmt(&self.0, f) } } #[doc(hidden)] pub struct Html<F>(pub F) where F: Fn(&mut ::std::fmt::Formatter) -> fmt::Result; impl<F> ToHtmlNode for Html<F> where F: Fn(&mut ::std::fmt::Formatter) -> fmt::Result, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (self.0)(f) } } #[macro_export] macro_rules! html_string { ($($tt:tt)*) => {{ let node = $crate::html!($($tt)*); format!("{}", $crate::HtmlString(node)) }} } #[doc(hidden)] pub mod hc;
lf, name: NoSpecial<'_>, f: &mut fmt::Formatter) -> Result { write!(f, " {}=\"", name.0)?; ToHtmlAttr::fmt(self, f)?; write!(f, "\"")?; Ok(()) }
function_block-function_prefixed
[ { "content": "fn html_impl(input: TokenStream) -> syn::Result<TokenStream> {\n\n let nodes = syn::parse2::<parse::HtmlNodes>(input).map_err(ctx(\"Parsing HTML input\"))?;\n\n let nodes = nodes\n\n .nodes\n\n .into_iter()\n\n .map(write_node)\n\n .collect::<syn::Result<Vec<Token...
Rust
test/src/utils.rs
Kryptoxic/ckb
3aaf85b5c3a64488cef4c914ab2bbf44051d9e85
use crate::{Net, Node, TXOSet}; use ckb_jsonrpc_types::{BlockTemplate, TransactionWithStatus, TxStatus}; use ckb_types::core::EpochNumber; use ckb_types::{ bytes::Bytes, core::{BlockNumber, BlockView, HeaderView, TransactionView}, h256, packed::{ Block, BlockTransactions, Byte32, CompactBlock, GetBlocks, RelayMessage, RelayTransaction, RelayTransactionHashes, RelayTransactions, SendBlock, SendHeaders, SyncMessage, }, prelude::*, H256, }; use std::convert::Into; use std::env; use std::fs::read_to_string; use std::path::PathBuf; use std::thread; use std::time::{Duration, Instant}; use tempfile::tempdir; pub const FLAG_SINCE_RELATIVE: u64 = 0b1000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000; pub const FLAG_SINCE_BLOCK_NUMBER: u64 = 0b000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000; pub const FLAG_SINCE_EPOCH_NUMBER: u64 = 0b010_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000; pub const FLAG_SINCE_TIMESTAMP: u64 = 0b100_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000; pub fn build_compact_block_with_prefilled(block: &BlockView, prefilled: Vec<usize>) -> Bytes { let prefilled = prefilled.into_iter().collect(); let compact_block = CompactBlock::build_from_block(block, &prefilled); RelayMessage::new_builder() .set(compact_block) .build() .as_bytes() } pub fn build_compact_block(block: &BlockView) -> Bytes { build_compact_block_with_prefilled(block, Vec::new()) } pub fn build_block_transactions(block: &BlockView) -> Bytes { let block_txs = BlockTransactions::new_builder() .block_hash(block.header().hash()) .transactions( block .transactions() .into_iter() .map(|view| view.data()) .skip(1) .pack(), ) .build(); RelayMessage::new_builder() .set(block_txs) .build() .as_bytes() } pub fn build_header(header: &HeaderView) -> Bytes { build_headers(&[header.clone()]) } pub fn build_headers(headers: &[HeaderView]) -> Bytes { let send_headers = SendHeaders::new_builder() .headers( headers .iter() .map(|view| view.data()) .collect::<Vec<_>>() .pack(), ) .build(); SyncMessage::new_builder() .set(send_headers) .build() .as_bytes() } pub fn build_block(block: &BlockView) -> Bytes { SyncMessage::new_builder() .set(SendBlock::new_builder().block(block.data()).build()) .build() .as_bytes() } pub fn build_get_blocks(hashes: &[Byte32]) -> Bytes { let get_blocks = GetBlocks::new_builder() .block_hashes(hashes.iter().map(ToOwned::to_owned).pack()) .build(); SyncMessage::new_builder() .set(get_blocks) .build() .as_bytes() } pub fn build_relay_txs(transactions: &[(TransactionView, u64)]) -> Bytes { let transactions = transactions.iter().map(|(tx, cycles)| { RelayTransaction::new_builder() .cycles(cycles.pack()) .transaction(tx.data()) .build() }); let txs = RelayTransactions::new_builder() .transactions(transactions.pack()) .build(); RelayMessage::new_builder().set(txs).build().as_bytes() } pub fn build_relay_tx_hashes(hashes: &[Byte32]) -> Bytes { let content = RelayTransactionHashes::new_builder() .tx_hashes(hashes.iter().map(ToOwned::to_owned).pack()) .build(); RelayMessage::new_builder().set(content).build().as_bytes() } pub fn new_block_with_template(template: BlockTemplate) -> BlockView { Block::from(template) .as_advanced_builder() .nonce(rand::random::<u128>().pack()) .build() } pub fn wait_until<F>(secs: u64, mut f: F) -> bool where F: FnMut() -> bool, { let timeout = tweaked_duration(secs); let start = Instant::now(); while Instant::now().duration_since(start) <= timeout { if f() { return true; } thread::sleep(Duration::new(1, 0)); } false } pub fn sleep(secs: u64) { thread::sleep(tweaked_duration(secs)); } fn tweaked_duration(secs: u64) -> Duration { let sec_coefficient = env::var("CKB_TEST_SEC_COEFFICIENT") .unwrap_or_default() .parse() .unwrap_or(1.0); Duration::from_secs((secs as f64 * sec_coefficient) as u64) } pub fn clear_messages(net: &Net) { while let Ok(_) = net.receive_timeout(Duration::new(3, 0)) {} } pub fn since_from_relative_block_number(block_number: BlockNumber) -> u64 { FLAG_SINCE_RELATIVE | FLAG_SINCE_BLOCK_NUMBER | block_number } pub fn since_from_absolute_block_number(block_number: BlockNumber) -> u64 { FLAG_SINCE_BLOCK_NUMBER | block_number } pub fn since_from_relative_epoch_number(epoch_number: EpochNumber) -> u64 { FLAG_SINCE_RELATIVE | FLAG_SINCE_EPOCH_NUMBER | epoch_number } pub fn since_from_absolute_epoch_number(epoch_number: EpochNumber) -> u64 { FLAG_SINCE_EPOCH_NUMBER | epoch_number } pub fn since_from_relative_timestamp(timestamp: u64) -> u64 { FLAG_SINCE_RELATIVE | FLAG_SINCE_TIMESTAMP | timestamp } pub fn since_from_absolute_timestamp(timestamp: u64) -> u64 { FLAG_SINCE_TIMESTAMP | timestamp } pub fn assert_send_transaction_fail(node: &Node, transaction: &TransactionView, message: &str) { let result = node .rpc_client() .inner() .send_transaction(transaction.data().into()); assert!( result.is_err(), "expect error \"{}\" but got \"Ok(())\"", message, ); let error = result.expect_err(&format!("transaction is invalid since {}", message)); let error_string = error.to_string(); assert!( error_string.contains(message), "expect error \"{}\" but got \"{}\"", message, error_string, ); } pub fn is_committed(tx_status: &TransactionWithStatus) -> bool { let committed_status = TxStatus::committed(h256!("0x0")); tx_status.tx_status.status == committed_status.status } pub fn temp_path() -> String { let tempdir = tempdir().expect("create tempdir failed"); let path = tempdir.path().to_str().unwrap().to_owned(); tempdir.close().expect("close tempdir failed"); path } pub fn generate_utxo_set(node: &Node, n: usize) -> TXOSet { let cellbase_maturity = node.consensus().cellbase_maturity(); node.generate_blocks(cellbase_maturity.index() as usize); let mut n_outputs = 0; let mut txs = Vec::new(); while n > n_outputs { node.generate_block(); let mature_number = node.get_tip_block_number() - cellbase_maturity.index(); let mature_block = node.get_block_by_number(mature_number); let mature_cellbase = mature_block.transaction(0).unwrap(); if mature_cellbase.outputs().is_empty() { continue; } let mature_utxos: TXOSet = TXOSet::from(&mature_cellbase); let tx = mature_utxos.boom(vec![node.always_success_cell_dep()]); n_outputs += tx.outputs().len(); txs.push(tx); } txs.iter().for_each(|tx| { node.submit_transaction(tx); }); while txs .iter() .any(|tx| !is_committed(&node.rpc_client().get_transaction(tx.hash()).unwrap())) { node.generate_blocks(node.consensus().finalization_delay_length() as usize); } let mut utxos = TXOSet::default(); txs.iter() .for_each(|tx| utxos.extend(Into::<TXOSet>::into(tx))); utxos.truncate(n); utxos } pub fn commit(node: &Node, committed: &[&TransactionView]) -> BlockView { let committed = committed .iter() .map(|t| t.to_owned().to_owned()) .collect::<Vec<_>>(); blank(node) .as_advanced_builder() .transactions(committed) .build() } pub fn propose(node: &Node, proposals: &[&TransactionView]) -> BlockView { let proposals = proposals.iter().map(|tx| tx.proposal_short_id()); blank(node) .as_advanced_builder() .proposals(proposals) .build() } pub fn blank(node: &Node) -> BlockView { let example = node.new_block(None, None, None); example .as_advanced_builder() .set_proposals(vec![]) .set_transactions(vec![example.transaction(0).unwrap()]) .set_uncles(vec![]) .build() } pub fn nodes_panicked(node_dirs: &[String]) -> bool { node_dirs.iter().any(|node_dir| { read_to_string(&node_log(&node_dir)) .expect("failed to read node's log") .contains("panicked at") }) } pub fn node_log(node_dir: &str) -> PathBuf { PathBuf::from(node_dir) .join("data") .join("logs") .join("run.log") }
use crate::{Net, Node, TXOSet}; use ckb_jsonrpc_types::{BlockTemplate, TransactionWithStatus, TxStatus}; use ckb_types::core::EpochNumber; use ckb_types::{ bytes::Bytes, core::{BlockNumber, BlockView, HeaderView, TransactionView}, h256, packed::{ Block, BlockTransactions, Byte32, CompactBlock, GetBlocks, RelayMessage, RelayTransaction, RelayTransactionHashes, RelayTransactions, SendBlock, SendHeaders, SyncMessage, }, prelude::*, H256, }; use std::convert::Into; use std::env; use std::fs::read_to_string; use std::path::PathBuf; use std::thread; use std::time::{Duration, Instant}; use tempfile::tempdir; pub const FLAG_SINCE_RELATIVE: u64 = 0b1000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000; pub const FLAG_SINCE_BLOCK_NUMBER: u64 = 0b000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000; pub const FLAG_SINCE_EPOCH_NUMBER: u64 = 0b010_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000; pub const FLAG_SINCE_TIMESTAMP: u64 = 0b100_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000; pub fn build_compact_block_with_prefilled(block: &BlockView, prefilled: Vec<usize>) -> Bytes { let prefilled = prefilled.into_iter().collect(); let compact_block = CompactBlock::build_from_block(block, &prefilled); RelayMessage::new_builder() .set(compact_block) .build() .as_bytes() } pub fn build_compact_block(block: &BlockView) -> Bytes { build_compact_block_with_prefilled(block, Vec::new()) } pub fn build_block_transactions(block: &BlockView) -> Bytes { let block_txs = BlockTransactions::new_builder() .block_hash(block.header().hash()) .transactions( block .transactions() .into_iter() .map(|view| view.data()) .skip(1) .pack(), ) .build(); RelayMessage::new_builder() .set(block_txs) .build() .as_bytes() } pub fn build_header(header: &HeaderView) -> Bytes { build_headers(&[header.clone()]) } pub fn build_headers(headers: &[HeaderView]) -> Bytes { let send_headers = SendHeaders::new_builder() .headers( headers .iter() .map(|view| view.data()) .collect::<Vec<_>>() .pack(), ) .build(); SyncMessage::new_builder() .set(send_headers) .build() .as_bytes() } pub fn build_block(block: &BlockView) -> Bytes { SyncMessage::new_builder() .set(SendBlock::new_builder().block(block.data()).build()) .build() .as_bytes() } pub fn build_get_blocks(hashes: &[Byte32]) -> Bytes { let get_blocks = GetBlocks::new_builder() .block_hashes(hashes.iter().map(ToOwned::to_owned).pack()) .build(); SyncMessage::new_builder() .set(get_blocks) .build() .as_bytes() } pub fn build_relay_txs(transactions: &[(TransactionView, u64)]) -> Bytes { let transactions = transactions.iter().map(|(tx, cycles)| { RelayTransaction::new_builder() .cycles(cycles.pack()) .transaction(tx.data()) .build() }); let txs = RelayTransactions::new_builder() .transactions(transactions.pack()) .build(); RelayMessage::new_builder().set(txs).build().as_bytes() } pub fn build_relay_tx_hashes(hashes: &[Byte32]) -> Bytes { let content = RelayTransactionHashes::new_builder() .tx_hashes(hashes.iter().map(ToOwned::to_owned).pack()) .build(); RelayMessage::new_builder().set(content).build().as_bytes() } pub fn new_block_with_template(template: BlockTemplate) -> BlockView { Block::from(template) .as_advanced_builder() .nonce(rand::random::<u128>().pack()) .build() } pub fn wait_until<F>(secs: u64, mut f: F) -> bool where F: FnMut() -> bool, { let timeout = tweaked_duration(secs); let start = Instant::now(); while Instant::now().duration_since(start) <= timeout { if f() { return true; } thread::sleep(Duration::new(1, 0)); } false } pub fn sleep(secs: u64) { thread::sleep(tweaked_duration(secs)); } fn
iew { let proposals = proposals.iter().map(|tx| tx.proposal_short_id()); blank(node) .as_advanced_builder() .proposals(proposals) .build() } pub fn blank(node: &Node) -> BlockView { let example = node.new_block(None, None, None); example .as_advanced_builder() .set_proposals(vec![]) .set_transactions(vec![example.transaction(0).unwrap()]) .set_uncles(vec![]) .build() } pub fn nodes_panicked(node_dirs: &[String]) -> bool { node_dirs.iter().any(|node_dir| { read_to_string(&node_log(&node_dir)) .expect("failed to read node's log") .contains("panicked at") }) } pub fn node_log(node_dir: &str) -> PathBuf { PathBuf::from(node_dir) .join("data") .join("logs") .join("run.log") }
tweaked_duration(secs: u64) -> Duration { let sec_coefficient = env::var("CKB_TEST_SEC_COEFFICIENT") .unwrap_or_default() .parse() .unwrap_or(1.0); Duration::from_secs((secs as f64 * sec_coefficient) as u64) } pub fn clear_messages(net: &Net) { while let Ok(_) = net.receive_timeout(Duration::new(3, 0)) {} } pub fn since_from_relative_block_number(block_number: BlockNumber) -> u64 { FLAG_SINCE_RELATIVE | FLAG_SINCE_BLOCK_NUMBER | block_number } pub fn since_from_absolute_block_number(block_number: BlockNumber) -> u64 { FLAG_SINCE_BLOCK_NUMBER | block_number } pub fn since_from_relative_epoch_number(epoch_number: EpochNumber) -> u64 { FLAG_SINCE_RELATIVE | FLAG_SINCE_EPOCH_NUMBER | epoch_number } pub fn since_from_absolute_epoch_number(epoch_number: EpochNumber) -> u64 { FLAG_SINCE_EPOCH_NUMBER | epoch_number } pub fn since_from_relative_timestamp(timestamp: u64) -> u64 { FLAG_SINCE_RELATIVE | FLAG_SINCE_TIMESTAMP | timestamp } pub fn since_from_absolute_timestamp(timestamp: u64) -> u64 { FLAG_SINCE_TIMESTAMP | timestamp } pub fn assert_send_transaction_fail(node: &Node, transaction: &TransactionView, message: &str) { let result = node .rpc_client() .inner() .send_transaction(transaction.data().into()); assert!( result.is_err(), "expect error \"{}\" but got \"Ok(())\"", message, ); let error = result.expect_err(&format!("transaction is invalid since {}", message)); let error_string = error.to_string(); assert!( error_string.contains(message), "expect error \"{}\" but got \"{}\"", message, error_string, ); } pub fn is_committed(tx_status: &TransactionWithStatus) -> bool { let committed_status = TxStatus::committed(h256!("0x0")); tx_status.tx_status.status == committed_status.status } pub fn temp_path() -> String { let tempdir = tempdir().expect("create tempdir failed"); let path = tempdir.path().to_str().unwrap().to_owned(); tempdir.close().expect("close tempdir failed"); path } pub fn generate_utxo_set(node: &Node, n: usize) -> TXOSet { let cellbase_maturity = node.consensus().cellbase_maturity(); node.generate_blocks(cellbase_maturity.index() as usize); let mut n_outputs = 0; let mut txs = Vec::new(); while n > n_outputs { node.generate_block(); let mature_number = node.get_tip_block_number() - cellbase_maturity.index(); let mature_block = node.get_block_by_number(mature_number); let mature_cellbase = mature_block.transaction(0).unwrap(); if mature_cellbase.outputs().is_empty() { continue; } let mature_utxos: TXOSet = TXOSet::from(&mature_cellbase); let tx = mature_utxos.boom(vec![node.always_success_cell_dep()]); n_outputs += tx.outputs().len(); txs.push(tx); } txs.iter().for_each(|tx| { node.submit_transaction(tx); }); while txs .iter() .any(|tx| !is_committed(&node.rpc_client().get_transaction(tx.hash()).unwrap())) { node.generate_blocks(node.consensus().finalization_delay_length() as usize); } let mut utxos = TXOSet::default(); txs.iter() .for_each(|tx| utxos.extend(Into::<TXOSet>::into(tx))); utxos.truncate(n); utxos } pub fn commit(node: &Node, committed: &[&TransactionView]) -> BlockView { let committed = committed .iter() .map(|t| t.to_owned().to_owned()) .collect::<Vec<_>>(); blank(node) .as_advanced_builder() .transactions(committed) .build() } pub fn propose(node: &Node, proposals: &[&TransactionView]) -> BlockV
random
[]
Rust
rust/core/src/matching/text.rs
DougAnderson444/deno-autosuggest
9d7b164063decd0bc9af3ec01e411c3a307f2843
use std::cmp::Ordering::{Equal, Less}; use std::cell::RefCell; use crate::tokenization::{Word, TextRef}; use super::WordMatch; use super::word::word_match; thread_local! { static RMATCHES: RefCell<Vec<Option<WordMatch>>> = RefCell::new(Vec::with_capacity(20)); static QMATCHES: RefCell<Vec<Option<WordMatch>>> = RefCell::new(Vec::with_capacity(20)); } pub fn text_match(rtext: &TextRef, qtext: &TextRef) -> (Vec<WordMatch>, Vec<WordMatch>) { RMATCHES.with(|rcell| { QMATCHES.with(|qcell| { let rmatches = &mut *rcell.borrow_mut(); let qmatches = &mut *qcell.borrow_mut(); rmatches.clear(); qmatches.clear(); rmatches.resize(rtext.words.len(), None); qmatches.resize(qtext.words.len(), None); for qword in qtext.words.iter() { if qmatches[qword.offset].is_some() { continue; } let qword = qword.to_view(qtext); let mut candidate: Option<(WordMatch, WordMatch)> = None; for rword in rtext.words.iter() { if rmatches[rword.offset].is_some() { continue; } let rword = rword.to_view(rtext); let mut stop = false; None.or_else(|| { let rnext = rtext.words.get(rword.offset + 1)?.to_view(rtext); if qword.len() < rword.len() + rword.dist(&rnext) { return None; } if rmatches.get(rword.offset + 1)?.is_some() { return None; } let (rmatch, qmatch) = word_match(&rword.join(&rnext), &qword)?; let (rmatch1, rmatch2) = rmatch.split(&rword, &rnext)?; let roffset1 = rmatch1.offset; let roffset2 = rmatch2.offset; let qoffset = qmatch.offset; rmatches[roffset1] = Some(rmatch1); rmatches[roffset2] = Some(rmatch2); qmatches[qoffset] = Some(qmatch); candidate.take(); stop = true; Some(()) }) .or_else(|| { let qnext = qtext.words.get(qword.offset + 1)?.to_view(qtext); if rword.len() < qword.len() + qword.dist(&qnext) { return None; } if qmatches.get(qword.offset + 1)?.is_some() { return None; } let (rmatch, qmatch) = word_match(&rword, &qword.join(&qnext))?; let (qmatch1, qmatch2) = qmatch.split(&qword, &qnext)?; let roffset = rmatch.offset; let qoffset1 = qmatch1.offset; let qoffset2 = qmatch2.offset; rmatches[roffset] = Some(rmatch); qmatches[qoffset1] = Some(qmatch1); qmatches[qoffset2] = Some(qmatch2); candidate.take(); stop = true; Some(()) }) .or_else(|| { let (rmatch2, qmatch2) = word_match(&rword, &qword)?; let score2 = rmatch2.match_len() - 2 * (rmatch2.typos.ceil() as usize); let score1 = candidate .as_ref() .map(|(m, _)| m.match_len() - 2 * (m.typos.ceil() as usize)) .unwrap_or(0); let replace = match (candidate.as_ref(), score1.cmp(&score2)) { (None, _) => true, (Some(_), Less) => true, (Some(_), Equal) if !rmatch2.func => true, _ => false, }; if replace { stop = !rmatch2.func; candidate = Some((rmatch2, qmatch2)); } Some(()) }); if stop { break; } } if let Some((rmatch, qmatch)) = candidate { let roffset = rmatch.offset; let qoffset = qmatch.offset; rmatches[roffset] = Some(rmatch); qmatches[qoffset] = Some(qmatch); } } let rmatches2 = rmatches.drain(..).filter_map(|m| m).collect::<Vec<_>>(); let qmatches2 = qmatches.drain(..).filter_map(|m| m).collect::<Vec<_>>(); (rmatches2, qmatches2) }) }) } #[cfg(test)] mod tests { use insta::assert_debug_snapshot; use crate::tokenization::{Text, TextOwn}; use crate::lang::{CharClass, lang_basic, lang_english, lang_spanish}; use super::{text_match}; fn text(s: &str) -> TextOwn { let lang = lang_basic(); Text::from_str(s) .split(&[CharClass::Punctuation, CharClass::Whitespace], &lang) .set_char_classes(&lang) } #[test] fn match_text_empty_both() { let rtext = text(""); let qtext = text("").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_empty_one() { let rtext = text(""); let qtext = text("mailbox").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); assert_debug_snapshot!(text_match(&qtext.to_ref(), &rtext.to_ref())); } #[test] fn match_text_singleton_equality() { let rtext = text("mailbox"); let qtext = text("mailbox").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_singleton_typos() { let rtext = text("mailbox"); let qtext = text("maiblox").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_pair_first() { let rtext = text("yellow mailbox"); let qtext = text("yelow").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_pair_second() { let rtext = text("yellow mailbox"); let qtext = text("maiblox").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_pair_unfinished() { let rtext = text("yellow mailbox"); let qtext = text("maiblox yel").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_intersection() { let rtext = text("small yellow metal mailbox"); let qtext = text("big malibox yelo").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_best_rword_first() { let rtext = text("theory theme"); let qtext = text("the").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_best_rword_nonfunc() { let lang = lang_english(); let rtext = text("the theme").set_pos(&lang); let qtext = text("the").fin(false).set_pos(&lang); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_best_rword_typos() { let lang = lang_spanish(); let rtext = text("Cepillo de dientes").set_pos(&lang); let qtext = text("de").fin(false).set_pos(&lang); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_regression_best_match() { let rtext = text("sneaky"); let qtext = text("sneak").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_joined_query() { let rtext = text("wifi router"); let qtext = text("wi fi router").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_joined_query_unfihished() { let rtext = text("microbiology"); let qtext = text("micro bio").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_joined_query_typos() { let rtext = text("microbiology"); let qtext = text("mcro byology").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_joined_query_short() { let rtext = text("t-light"); let qtext = text("tli").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_joined_record() { let rtext = text("wi fi router"); let qtext = text("wifi router").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_joined_record_typos() { let rtext = text("micro biology"); let qtext = text("mcrobiology").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_joined_record_unfinished() { let rtext = text("micro biology"); let qtext = text("microbio").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_joined_regression_1() { let rtext = text("special, year"); let qtext = text("especiall").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_joined_regression_2() { let rtext1 = text("50's"); let rtext2 = text("500w"); let qtext = text("50s").fin(false); assert_debug_snapshot!(text_match(&rtext1.to_ref(), &qtext.to_ref())); assert_debug_snapshot!(text_match(&rtext2.to_ref(), &qtext.to_ref())); } }
use std::cmp::Ordering::{Equal, Less}; use std::cell::RefCell; use crate::tokenization::{Word, TextRef}; use super::WordMatch; use super::word::word_match; thread_local! { static RMATCHES: RefCell<Vec<Option<WordMatch>>> = RefCell::new(Vec::with_capacity(20)); static QMATCHES: RefCell<Vec<Option<WordMatch>>> = RefCell::new(Vec::with_capacity(20)); }
#[cfg(test)] mod tests { use insta::assert_debug_snapshot; use crate::tokenization::{Text, TextOwn}; use crate::lang::{CharClass, lang_basic, lang_english, lang_spanish}; use super::{text_match}; fn text(s: &str) -> TextOwn { let lang = lang_basic(); Text::from_str(s) .split(&[CharClass::Punctuation, CharClass::Whitespace], &lang) .set_char_classes(&lang) } #[test] fn match_text_empty_both() { let rtext = text(""); let qtext = text("").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_empty_one() { let rtext = text(""); let qtext = text("mailbox").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); assert_debug_snapshot!(text_match(&qtext.to_ref(), &rtext.to_ref())); } #[test] fn match_text_singleton_equality() { let rtext = text("mailbox"); let qtext = text("mailbox").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_singleton_typos() { let rtext = text("mailbox"); let qtext = text("maiblox").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_pair_first() { let rtext = text("yellow mailbox"); let qtext = text("yelow").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_pair_second() { let rtext = text("yellow mailbox"); let qtext = text("maiblox").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_pair_unfinished() { let rtext = text("yellow mailbox"); let qtext = text("maiblox yel").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_intersection() { let rtext = text("small yellow metal mailbox"); let qtext = text("big malibox yelo").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_best_rword_first() { let rtext = text("theory theme"); let qtext = text("the").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_best_rword_nonfunc() { let lang = lang_english(); let rtext = text("the theme").set_pos(&lang); let qtext = text("the").fin(false).set_pos(&lang); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_best_rword_typos() { let lang = lang_spanish(); let rtext = text("Cepillo de dientes").set_pos(&lang); let qtext = text("de").fin(false).set_pos(&lang); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_regression_best_match() { let rtext = text("sneaky"); let qtext = text("sneak").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_joined_query() { let rtext = text("wifi router"); let qtext = text("wi fi router").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_joined_query_unfihished() { let rtext = text("microbiology"); let qtext = text("micro bio").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_joined_query_typos() { let rtext = text("microbiology"); let qtext = text("mcro byology").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_joined_query_short() { let rtext = text("t-light"); let qtext = text("tli").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_joined_record() { let rtext = text("wi fi router"); let qtext = text("wifi router").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_joined_record_typos() { let rtext = text("micro biology"); let qtext = text("mcrobiology").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_joined_record_unfinished() { let rtext = text("micro biology"); let qtext = text("microbio").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_joined_regression_1() { let rtext = text("special, year"); let qtext = text("especiall").fin(false); assert_debug_snapshot!(text_match(&rtext.to_ref(), &qtext.to_ref())); } #[test] fn match_text_joined_regression_2() { let rtext1 = text("50's"); let rtext2 = text("500w"); let qtext = text("50s").fin(false); assert_debug_snapshot!(text_match(&rtext1.to_ref(), &qtext.to_ref())); assert_debug_snapshot!(text_match(&rtext2.to_ref(), &qtext.to_ref())); } }
pub fn text_match(rtext: &TextRef, qtext: &TextRef) -> (Vec<WordMatch>, Vec<WordMatch>) { RMATCHES.with(|rcell| { QMATCHES.with(|qcell| { let rmatches = &mut *rcell.borrow_mut(); let qmatches = &mut *qcell.borrow_mut(); rmatches.clear(); qmatches.clear(); rmatches.resize(rtext.words.len(), None); qmatches.resize(qtext.words.len(), None); for qword in qtext.words.iter() { if qmatches[qword.offset].is_some() { continue; } let qword = qword.to_view(qtext); let mut candidate: Option<(WordMatch, WordMatch)> = None; for rword in rtext.words.iter() { if rmatches[rword.offset].is_some() { continue; } let rword = rword.to_view(rtext); let mut stop = false; None.or_else(|| { let rnext = rtext.words.get(rword.offset + 1)?.to_view(rtext); if qword.len() < rword.len() + rword.dist(&rnext) { return None; } if rmatches.get(rword.offset + 1)?.is_some() { return None; } let (rmatch, qmatch) = word_match(&rword.join(&rnext), &qword)?; let (rmatch1, rmatch2) = rmatch.split(&rword, &rnext)?; let roffset1 = rmatch1.offset; let roffset2 = rmatch2.offset; let qoffset = qmatch.offset; rmatches[roffset1] = Some(rmatch1); rmatches[roffset2] = Some(rmatch2); qmatches[qoffset] = Some(qmatch); candidate.take(); stop = true; Some(()) }) .or_else(|| { let qnext = qtext.words.get(qword.offset + 1)?.to_view(qtext); if rword.len() < qword.len() + qword.dist(&qnext) { return None; } if qmatches.get(qword.offset + 1)?.is_some() { return None; } let (rmatch, qmatch) = word_match(&rword, &qword.join(&qnext))?; let (qmatch1, qmatch2) = qmatch.split(&qword, &qnext)?; let roffset = rmatch.offset; let qoffset1 = qmatch1.offset; let qoffset2 = qmatch2.offset; rmatches[roffset] = Some(rmatch); qmatches[qoffset1] = Some(qmatch1); qmatches[qoffset2] = Some(qmatch2); candidate.take(); stop = true; Some(()) }) .or_else(|| { let (rmatch2, qmatch2) = word_match(&rword, &qword)?; let score2 = rmatch2.match_len() - 2 * (rmatch2.typos.ceil() as usize); let score1 = candidate .as_ref() .map(|(m, _)| m.match_len() - 2 * (m.typos.ceil() as usize)) .unwrap_or(0); let replace = match (candidate.as_ref(), score1.cmp(&score2)) { (None, _) => true, (Some(_), Less) => true, (Some(_), Equal) if !rmatch2.func => true, _ => false, }; if replace { stop = !rmatch2.func; candidate = Some((rmatch2, qmatch2)); } Some(()) }); if stop { break; } } if let Some((rmatch, qmatch)) = candidate { let roffset = rmatch.offset; let qoffset = qmatch.offset; rmatches[roffset] = Some(rmatch); qmatches[qoffset] = Some(qmatch); } } let rmatches2 = rmatches.drain(..).filter_map(|m| m).collect::<Vec<_>>(); let qmatches2 = qmatches.drain(..).filter_map(|m| m).collect::<Vec<_>>(); (rmatches2, qmatches2) }) }) }
function_block-full_function
[ { "content": "fn using_store<T, F>(f: F) -> T where F: (FnOnce(&mut Store) -> T) {\n\n init_store();\n\n STORE.with(|cell| {\n\n let store_opt = &mut *cell.borrow_mut();\n\n let store = store_opt.as_mut().unwrap();\n\n f(store)\n\n })\n\n}\n\n\n\n\n", "file_path": "rust/core/te...
Rust
src/ether.rs
simmsb/jnet
2b5c94b0588bcdaf70eb058b6bd8641433250c8a
use core::{ fmt, ops::{Range, RangeFrom}, }; use as_slice::{AsMutSlice, AsSlice}; use byteorder::{ByteOrder, NetworkEndian as NE}; use cast::{u16, usize}; use owning_slice::{IntoSliceFrom, Truncate}; use crate::{arp, ipv4, ipv6, mac, traits::UncheckedIndex, Invalid}; /* Frame format */ const DESTINATION: Range<usize> = 0..6; const SOURCE: Range<usize> = 6..12; const TYPE: Range<usize> = 12..14; const PAYLOAD: RangeFrom<usize> = 14..; pub const HEADER_SIZE: u8 = TYPE.end as u8; #[derive(Clone, Copy)] pub struct Frame<BUFFER> where BUFFER: AsSlice<Element = u8>, { buffer: BUFFER, } impl<B> Frame<B> where B: AsSlice<Element = u8>, { /* Constructors */ pub fn new(buffer: B) -> Self { assert!(buffer.as_slice().len() >= usize(HEADER_SIZE)); Frame { buffer } } pub fn parse(bytes: B) -> Result<Self, B> { if bytes.as_slice().len() < usize(HEADER_SIZE) { Err(bytes) } else { Ok(Frame { buffer: bytes }) } } /* Getters */ pub fn get_destination(&self) -> mac::Addr { unsafe { mac::Addr(*(self.as_slice().as_ptr().add(DESTINATION.start) as *const _)) } } pub fn get_source(&self) -> mac::Addr { unsafe { mac::Addr(*(self.as_slice().as_ptr().add(SOURCE.start) as *const _)) } } pub fn get_type(&self) -> Type { NE::read_u16(&self.header_()[TYPE]).into() } pub fn payload(&self) -> &[u8] { unsafe { &self.as_slice().rf(PAYLOAD) } } /* Miscellaneous */ pub fn as_bytes(&self) -> &[u8] { self.as_slice() } pub fn free(self) -> B { self.buffer } pub fn len(&self) -> u16 { u16(self.as_bytes().len()).unwrap() } /* Private */ fn as_slice(&self) -> &[u8] { self.buffer.as_slice() } fn header_(&self) -> &[u8; HEADER_SIZE as usize] { debug_assert!(self.as_slice().len() >= HEADER_SIZE as usize); unsafe { &*(self.as_slice().as_ptr() as *const _) } } } impl<B> Frame<B> where B: AsSlice<Element = u8> + AsMutSlice<Element = u8>, { /* Setters */ pub fn set_destination(&mut self, addr: mac::Addr) { self.header_mut_()[DESTINATION].copy_from_slice(&addr.0) } pub fn set_source(&mut self, addr: mac::Addr) { self.header_mut_()[SOURCE].copy_from_slice(&addr.0) } pub fn set_type(&mut self, type_: Type) { NE::write_u16(&mut self.header_mut_()[TYPE], type_.into()) } /* Miscellaneous */ pub fn payload_mut(&mut self) -> &mut [u8] { &mut self.as_mut_slice()[PAYLOAD] } /* Private */ fn as_mut_slice(&mut self) -> &mut [u8] { self.buffer.as_mut_slice() } fn header_mut_(&mut self) -> &mut [u8; HEADER_SIZE as usize] { debug_assert!(self.as_slice().len() >= HEADER_SIZE as usize); unsafe { &mut *(self.as_mut_slice().as_mut_ptr() as *mut _) } } } impl<B> Frame<B> where B: AsSlice<Element = u8> + IntoSliceFrom<u8>, { pub fn into_payload(self) -> B::SliceFrom { self.buffer.into_slice_from(HEADER_SIZE) } } impl<B> Frame<B> where B: AsSlice<Element = u8> + AsMutSlice<Element = u8> + Truncate<u8>, { pub fn arp<F>(&mut self, f: F) where F: FnOnce(&mut arp::Packet<&mut [u8]>), { self.set_type(Type::Arp); let sha = self.get_source(); let len = { let mut arp = arp::Packet::new(self.payload_mut()); arp.set_sha(sha); f(&mut arp); arp.len() }; self.buffer.truncate(HEADER_SIZE + len); } } impl<B> Frame<B> where B: AsSlice<Element = u8> + AsMutSlice<Element = u8> + Truncate<u16>, { pub fn ipv4<F>(&mut self, f: F) where F: FnOnce(&mut ipv4::Packet<&mut [u8], Invalid>), { self.set_type(Type::Ipv4); let len = { let mut ip = ipv4::Packet::new(self.payload_mut()); f(&mut ip); ip.update_checksum().get_total_length() }; self.buffer.truncate(u16(HEADER_SIZE) + len); } pub fn ipv6<F>(&mut self, f: F) where F: FnOnce(&mut ipv6::Packet<&mut [u8]>), { self.set_type(Type::Ipv6); let len = { let mut ip = ipv6::Packet::new(self.payload_mut()); f(&mut ip); ip.get_length() + u16(ipv6::HEADER_SIZE) }; self.buffer.truncate(u16(HEADER_SIZE) + len); } } impl<B> fmt::Debug for Frame<B> where B: AsSlice<Element = u8>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("ether::Frame") .field("destination", &self.get_destination()) .field("source", &self.get_source()) .field("type", &self.get_type()) .finish() } } full_range!( u16, #[derive(Clone, Copy, Debug, PartialEq)] pub enum Type { Ipv4 = 0x0800, Arp = 0x0806, Ipv6 = 0x86DD, } ); #[cfg(test)] mod tests { use crate::ether; #[test] fn new() { const SZ: u16 = 128; let mut chunk = [0; SZ as usize]; let buf = &mut chunk; let eth = ether::Frame::new(buf); assert_eq!(eth.len(), SZ); } }
use core::{ fmt, ops::{Range, RangeFrom}, }; use as_slice::{AsMutSlice, AsSlice}; use byteorder::{ByteOrder, NetworkEndian as NE}; use cast::{u16, usize}; use owning_slice::{IntoSliceFrom, Truncate}; use crate::{arp, ipv4, ipv6, mac, traits::UncheckedIndex, Invalid}; /* Frame format */ const DESTINATION: Range<usize> = 0..6; const SOURCE: Range<usize> = 6..12; const TYPE: Range<usize> = 12..14; const PAYLOAD: RangeFrom<usize> = 14..; pub const HEADER_SIZE: u8 = TYPE.end as u8; #[derive(Clone, Copy)] pub struct Frame<BUFFER> where BUFFER: AsSlice<Element = u8>, { buffer: BUFFER, } impl<B> Frame<B> where B: AsSlice<Element = u8>, { /* Constructors */ pub fn new(buffer: B) -> Self { assert!(buffer.as_slice().len() >= usize(HEADER_SIZE)); Frame { buffer } } pub fn parse(bytes: B) -> Result<Self, B> { if bytes.as_slice().len() < usize(HEADER_SIZE) { Err(bytes) } else { Ok(Frame { buffer: bytes }) } } /* Getters */ pub fn get_destination(&self) -> mac::Addr { unsafe { mac::Addr(*(self.as_slice().as_ptr().add(DESTINATION.start) as *const _)) } } pub fn get_source(&self) -> mac::Addr { unsafe { mac::Addr(*(self.as_slice().as_ptr().add(SOURCE.start) as *const _)) } } pub fn get_type(&self) -> Type { NE::read_u16(&self.header_()[TYPE]).into() } pub fn payload(&self) -> &[u8] { unsafe { &self.as_slice().rf(PAYLOAD) } } /* Miscellaneous */ pub fn as_bytes(&self) -> &[u8] { self.as_slice() } pub fn free(self) -> B { self.buffer } pub fn len(&self) -> u16 { u16(self.as_bytes().len()).unwrap() } /* Private */ fn as_slice(&self) -> &[u8] { self.buffer.as_slice() } fn header_(&self) -> &[u8; HEADER_SIZE as usize] { debug_assert!(self.as_slice().len() >= HEADER_SIZE as usize); unsafe { &*(self.as_slice().as_ptr() as *const _) } } } impl<B> Frame<B> where B: AsSlice<Element = u8> + AsMutSlice<Element = u8>, { /* Setters */ pub fn set_destination(&mut self, addr: mac::Addr) { self.header_mut_()[DESTINATION].copy_from_slice(&addr.0) } pub fn set_source(&mut self, addr: mac::Addr) { self.header_mut_()[SOURCE].copy_from_slice(&addr.0) } pub fn set_type(&mut self, type_: Type) { NE::write_u16(&mut self.header_mut_()[TYPE], type_.into()) } /* Miscellaneous */ pub fn payload_mut(&mut self) -> &mut [u8] { &mut self.as_mut_slice()[PAYLOAD] } /* Private */ fn as_mut_slice(&mut self) -> &mut [u8] { self.buffer.as_mut_slice() } fn header_mut_(&mut self) -> &mut [u8; HEADER_SIZE as usize] { debug_assert!(self.as_slice().len() >= HEADER_SIZE as usize); unsafe { &mut *(self.as_mut_slice().as_mut_ptr() as *mut _) } } } impl<B> Frame<B> where B: AsSlice<Element = u8> + IntoSliceFrom<u8>, { pub fn into_payload(self) -> B::SliceFrom { self.buffer.into_slice_from(HEADER_SIZE) } } impl<B> Frame<B> where B: AsSlice<Element = u8> + AsMutSlice<Element = u8> + Truncate<u8>, { pub fn arp<F>(&mut self, f: F) where F: FnOnce(&mut arp::Packet<&mut [u8]>), { self.set_type(Type::Arp); let sha = self.get_source(); let len = { let mut arp = arp::Packet::new(self.payload_mut()); arp.set_sha(sha); f(&mut arp); arp.len() }; self.buffer.truncate(HEADER_SIZE + len); } } impl<B> Frame<B> where B: AsSlice<Element = u8> + AsMutSlice<Element = u8> + Truncate<u16>, { pub fn ipv4<F>(&mut self, f: F) where F: FnOnce(&mut ipv4::Packet<&mut [u8], Invalid>), { self.set_type(Type::Ipv4); let len = { let mut ip = ipv4::Packet::new(self.payload_mut()); f(&mut ip); ip.update_checksum().get_total_length() }; self.buffer.truncate(u16(HEADER_SIZE) + len); } pub fn ipv6<F>(&mut self, f: F) where F: FnOnce(&mut ipv6::Packet<&mut [u8]>), { self.set_type(Type::Ipv6); let len = { let mut ip = ipv6::Packet::new(self.payload_mut()); f(&mut ip); ip.get_length() + u16(ipv6::HEADER_SIZE) }; self.buffer.truncate(u16(HEADER_SIZE) + len); } } impl<B> fmt::Debug for Frame<B> where B: AsSlice<Element = u8>, {
} full_range!( u16, #[derive(Clone, Copy, Debug, PartialEq)] pub enum Type { Ipv4 = 0x0800, Arp = 0x0806, Ipv6 = 0x86DD, } ); #[cfg(test)] mod tests { use crate::ether; #[test] fn new() { const SZ: u16 = 128; let mut chunk = [0; SZ as usize]; let buf = &mut chunk; let eth = ether::Frame::new(buf); assert_eq!(eth.len(), SZ); } }
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("ether::Frame") .field("destination", &self.get_destination()) .field("source", &self.get_source()) .field("type", &self.get_type()) .finish() }
function_block-full_function
[ { "content": "fn our_nl_addr() -> ipv6::Addr {\n\n MAC.into_link_local_address()\n\n}\n\n\n", "file_path": "firmware/examples/ipv6.rs", "rank": 0, "score": 166475.85127620032 }, { "content": "/// Serializes the `value` into the given `buffer`\n\npub fn write<'a, T>(value: &T, buffer: &'a ...
Rust
src/driver.rs
king6cong/iron-kaleidoscope
fed9a75aa211a829a0b2b099f4bcfcef2079d034
use std::io; use std::io::Write; use iron_llvm::core::value::Value; use iron_llvm::target; use builder; use builder::{IRBuilder, ModuleProvider}; use jitter; use jitter::JITter; use lexer::*; use parser::*; use filer; pub use self::Stage::{ Exec, IR, AST, Tokens }; #[derive(PartialEq, Clone, Debug)] pub enum Stage { Exec, IR, AST, Tokens } pub fn main_loop(stage: Stage) { let stdin = io::stdin(); let mut stdout = io::stdout(); let mut input = String::new(); let mut parser_settings = default_parser_settings(); /* //< ch-2 let mut ir_container = builder::SimpleModuleProvider::new("main"); //> ch-2 */ let mut ir_container : Box<JITter> = if stage == Exec { target::initilalize_native_target(); target::initilalize_native_asm_printer(); jitter::init(); Box::new( jitter::MCJITter::new("main") ) } else { Box::new( builder::SimpleModuleProvider::new("main") ) }; let mut builder_context = builder::Context::new(); match filer::load_stdlib(&mut parser_settings, &mut builder_context, ir_container.get_module_provider()) { Ok((value, runnable)) => if runnable && stage == Exec { ir_container.run_function(value); }, Err(err) => print!("Error occured during stdlib loading: {}\n", err) }; 'main: loop { print!("> "); stdout.flush().unwrap(); input.clear(); stdin.read_line(&mut input).ok().expect("Failed to read line"); if input.as_str() == ".quit\n" { break; } else if &input[0..5] == ".load" { let mut path = input[6..].to_string(); match path.pop() { Some(_) => (), None => { print!("Error occured during loading: empty path\n"); continue; } }; match filer::load_ks(path, &mut parser_settings, &mut builder_context, ir_container.get_module_provider()) { Ok((value, runnable)) => if runnable && stage == Exec { ir_container.run_function(value); }, Err(err) => print!("Error occured during loading: {}\n", err) }; continue; } else if &input[0..5] == ".dump" { let mut path = input[6..].to_string(); match path.pop() { Some(_) => (), None => { print!("Error occured during dumping: empty path\n"); continue; } }; match filer::dump_bitcode(&path, ir_container.get_module_provider()) { Ok(_) => (), Err(_) => print!("Error occured during dumping\n") }; continue; } else if input.as_str() == ".help\n" { print!("Enter Kaleidoscope expressions or special commands.\n"); print!("Special commands are:\n"); print!(".quit -- quit\n"); print!(".load <path> -- load .ks file\n"); print!(".dump <path> -- dump bitcode of currently open module\n"); print!(".help -- show this help message\n"); continue; } let mut ast = Vec::new(); let mut prev = Vec::new(); loop { let tokens = tokenize(input.as_str()); if stage == Tokens { println!("{:?}", tokens); continue 'main } prev.extend(tokens.into_iter()); let parsing_result = parse(prev.as_slice(), ast.as_slice(), &mut parser_settings); match parsing_result { Ok((parsed_ast, rest)) => { ast.extend(parsed_ast.into_iter()); if rest.is_empty() { break } else { prev = rest; } }, Err(message) => { println!("Error occured: {}", message); continue 'main } } print!(". "); stdout.flush().unwrap(); input.clear(); stdin.read_line(&mut input).ok().expect("Failed to read line"); } if stage == AST { println!("{:?}", ast); continue } match ast.codegen(&mut builder_context, ir_container.get_module_provider() /* //< ch-2 &mut ir_container) { Ok((value, _)) => value.dump(), //> ch-2 */ /*j*/ ) { Ok((value, runnable)) => if runnable && stage == Exec { println!("=> {}", ir_container.run_function(value)); } else { value.dump(); }, Err(message) => println!("Error occured: {}", message) } } if stage == IR /*jw*/ || stage == Exec /*jw*/ { ir_container.dump(); } }
use std::io; use std::io::Write; use iron_llvm::core::value::Value; use iron_llvm::target; use builder; use builder::{IRBuilder, ModuleProvider}; use jitter; use jitter::JITter; use lexer::*; use parser::*; use filer; pub use self::Stage::{ Exec, IR, AST, Tokens }; #[derive(PartialEq, Clone, Debug)] pub enum Stage { Exec, IR, AST, Tokens } pub fn main_loop(stage: Stage) { let stdin = io::stdin(); let mut stdout = io::stdout(); let mut input = String::new(); let mut parser_settings = default_parser_settings(); /* //< ch-2 let mut ir_container = builder::SimpleModuleProvider::new("main"); //> ch-2 */ let mut ir_container : Box<JITter> = if stage == Exec { target::initilalize_native_target(); target::initilalize_native_asm_printer(); jitter::init(); Box::new( jitter::MCJITter::new("main") ) } else { Box::new( builder::SimpleModuleProvider::new("main") ) }; let mut builder_context = builder::Context::new(); match filer::load_stdlib(&mut parser_settings, &mut builder_context, ir_container.get_module_provider()) { Ok((value, runnable)) => if runnable && stage == Exec { ir_container.run_function(value); }, Err(err) => print!("Error occured during stdlib loading: {}\n", err) }; 'main: loop { print!("> "); stdout.flush().unwrap(); input.clear(); stdin.read_line(&mut input).ok().expect("Failed to read line"); if input.as_str() == ".quit\n" { break; } else if &input[0..5] == ".load" { let mut path = input[6..].to_string(); match path.pop() { Some(_) => (), None => { print!("Error occured during loading: empty path\n"); continue; } }; match filer::load_ks(path, &mut parser_settings, &mut builder_context, ir_container.get_module_provider()) { Ok((value, runnable)) => if runnable && stage == Exec { ir_container.run_function(value); }, Err(err) => print!("Error occured during loading: {}\n", err) }; continue; } else if &input[0..5] == ".dump" { let mut path = input[6..].to_string(); match path.pop() { Some(_) => (), None => { print!("Error occured during dumping: empty path\n"); continue; } }; match filer::dump_bitcode(&path, ir_container.get_module_provider()) { Ok(_) => (), Err(_) => print!("Error occured during dumping\n") }; continue; } else if input.as_str() == ".help\n" { print!("Enter Kaleidoscope expressions or special commands.\n"); print!("Special commands are:\n"); print!(".quit -- quit\n"); print!(".load <path> -- load .ks file\n"); print!(".dump <path> -- dump bitcode of currently open module\n"); print!(".help -- show this help message\n"); continue; } let mut ast = Vec::new(); let mut prev = Vec::new(); loop { let tokens = tokenize(input.as_str()); if stage == Tokens { println!("{:?}", tokens); continue 'main } prev.extend(tokens.into_iter()); let parsing_result = parse(prev.as_slice(), ast.as_slice(), &mut parser_settings); match parsing_result { Ok((parsed_ast, rest)) => { ast.extend(parsed_ast.into_iter()); if rest.is_empty() { break } else { prev = rest; } }, Err(message) => { println!("Error occured: {}", messag
e); continue 'main } } print!(". "); stdout.flush().unwrap(); input.clear(); stdin.read_line(&mut input).ok().expect("Failed to read line"); } if stage == AST { println!("{:?}", ast); continue } match ast.codegen(&mut builder_context, ir_container.get_module_provider() /* //< ch-2 &mut ir_container) { Ok((value, _)) => value.dump(), //> ch-2 */ /*j*/ ) { Ok((value, runnable)) => if runnable && stage == Exec { println!("=> {}", ir_container.run_function(value)); } else { value.dump(); }, Err(message) => println!("Error occured: {}", message) } } if stage == IR /*jw*/ || stage == Exec /*jw*/ { ir_container.dump(); } }
function_block-function_prefixed
[ { "content": "pub fn dump_bitcode(path: &str, module_provider: &mut builder::ModuleProvider) -> Result<(), ()> {\n\n write_bitcode_to_file(module_provider.get_module(), path)\n\n}\n", "file_path": "src/filer.rs", "rank": 0, "score": 360041.82408747525 }, { "content": "pub fn load_stdlib(p...
Rust
application/apps/indexer/indexer_base/src/utils.rs
ir210/chipmunk
e2664efa3d3c0d80b67f3b324aa5289f6941ab23
use failure::{err_msg, Error}; use std::char; use std::fmt::Display; use std::fs; use std::io::{BufReader, Read, Seek, SeekFrom}; use std::path; use std::str; pub const ROW_NUMBER_SENTINAL: char = '\u{0002}'; pub const PLUGIN_ID_SENTINAL: char = '\u{0003}'; pub const SENTINAL_LENGTH: usize = 1; pub const POSIX_TIMESTAMP_LENGTH: usize = 13; const PEEK_END_SIZE: usize = 12; #[inline] pub fn is_newline(c: char) -> bool { match c { '\x0a' => true, '\x0d' => true, _ => false, } } #[inline] pub fn create_tagged_line_d<T: Display>( tag: &str, out_buffer: &mut dyn std::io::Write, trimmed_line: T, line_nr: usize, with_newline: bool, ) -> std::io::Result<usize> { let s = format!( "{}{}{}{}{}{}{}{}", trimmed_line, PLUGIN_ID_SENTINAL, tag, PLUGIN_ID_SENTINAL, ROW_NUMBER_SENTINAL, line_nr, ROW_NUMBER_SENTINAL, if with_newline { "\n" } else { "" }, ); let len = s.len(); write!(out_buffer, "{}", s)?; Ok(len) } #[inline] pub fn create_tagged_line( tag: &str, out_buffer: &mut dyn std::io::Write, trimmed_line: &str, line_nr: usize, with_newline: bool, ) -> std::io::Result<usize> { if with_newline { writeln!( out_buffer, "{}", format_args!( "{}{}{}{}{}{}{}", trimmed_line, PLUGIN_ID_SENTINAL, tag, PLUGIN_ID_SENTINAL, ROW_NUMBER_SENTINAL, line_nr, ROW_NUMBER_SENTINAL, ), )?; } else { write!( out_buffer, "{}", format_args!( "{}{}{}{}{}{}{}", trimmed_line, PLUGIN_ID_SENTINAL, tag, PLUGIN_ID_SENTINAL, ROW_NUMBER_SENTINAL, line_nr, ROW_NUMBER_SENTINAL, ), )?; } Ok(trimmed_line.len() + 4 * SENTINAL_LENGTH + tag.len() + linenr_length(line_nr) + 1) } #[inline] pub fn extended_line_length( trimmed_len: usize, tag_len: usize, line_nr: usize, has_newline: bool, ) -> usize { trimmed_len + 4 * SENTINAL_LENGTH + tag_len + linenr_length(line_nr) + if has_newline { 1 } else { 0 } } pub fn linenr_length(linenr: usize) -> usize { if linenr == 0 { return 1; }; let nr = linenr as f64; 1 + nr.log10().floor() as usize } #[inline] pub fn next_line_nr(path: &std::path::Path) -> Result<usize, Error> { if !path.exists() { return Ok(0); } let file = fs::File::open(path).expect("opening file did not work"); let file_size = file.metadata().expect("could not read file metadata").len(); if file_size == 0 { return Ok(0); }; let mut reader = BufReader::new(file); let seek_offset: i64 = -(std::cmp::min(file_size - 1, PEEK_END_SIZE as u64) as i64); match reader.seek(SeekFrom::End(seek_offset as i64)) { Ok(_) => (), Err(e) => { return Err(err_msg(format!( "could not read last entry in file {:?}", e ))); } }; let size_of_slice = seek_offset.abs() as usize; let mut buf: Vec<u8> = vec![0; size_of_slice]; reader .read_exact(&mut buf) .expect("reading to buffer should succeed"); for i in 0..size_of_slice - 1 { if buf[i] == (PLUGIN_ID_SENTINAL as u8) && buf[i + 1] == ROW_NUMBER_SENTINAL as u8 { let row_slice = &buf[i + 2..]; let row_string = std::str::from_utf8(row_slice).expect("could not parse row number"); let row_nr: usize = row_string .trim_end_matches(is_newline) .trim_end_matches(ROW_NUMBER_SENTINAL) .parse() .expect("expected number was was none"); return Ok(row_nr + 1); } } Err(err_msg(format!( "did not find row number in line: {:X?}", buf ))) } pub fn get_out_file_and_size( append: bool, out_path: &path::PathBuf, ) -> Result<(fs::File, usize), Error> { let out_file: std::fs::File = if append { std::fs::OpenOptions::new() .append(true) .create(true) .open(out_path)? } else { std::fs::File::create(out_path)? }; let current_out_file_size = out_file.metadata().map(|md| md.len() as usize)?; Ok((out_file, current_out_file_size)) } #[inline] pub fn report_progress( line_nr: usize, current_byte_index: usize, processed_bytes: usize, source_file_size: usize, progress_every_n_lines: usize, ) { if line_nr % progress_every_n_lines == 0 { eprintln!( "processed {} lines -- byte-index {} ({} %)", line_nr, current_byte_index, (processed_bytes as f32 / source_file_size as f32 * 100.0).round() ); } } pub fn get_processed_bytes(append: bool, out: &path::PathBuf) -> u64 { if append { match fs::metadata(out) { Ok(metadata) => metadata.len(), Err(_) => 0, } } else { 0 } }
use failure::{err_msg, Error}; use std::char; use std::fmt::Display; use std::fs; use std::io::{BufReader, Read, Seek, SeekFrom}; use std::path; use std::str; pub const ROW_NUMBER_SENTINAL: char = '\u{0002}'; pub const PLUGIN_ID_SENTINAL: char = '\u{0003}'; pub const SENTINAL_LENGTH: usize = 1; pub const POSIX_TIMESTAMP_LENGTH: usize = 13; const PEEK_END_SIZE: usize = 12; #[inline] pub fn is_newline(c: char) -> bool { match c { '\x0a' => true, '\x0d' => true, _ => false, } } #[inline] pub fn create_tagged_line_d<T: Display>( tag: &str, out_buffer: &mut dyn std::io::Write, trimmed_line: T, line_nr: usize, with_newline: bool, ) -> std::io::Result<usize> { let s = format!( "{}{}{}{}{}{}{}{}", trimmed_line, PLUGIN_ID_SENTINAL, tag, PLUGIN_ID_SENTINAL, ROW_NUMBER_SENTINAL, line_nr, ROW_NUMBER_SENTINAL, if with_newline { "\n" } else { "" }, ); let len = s.len(); write!(out_buffer, "{}", s)?; Ok(len) } #[inline] pub fn create_tagged_line( tag: &str, out_buffer: &mut dyn std::io::Write, trimmed_line: &str, line_nr: usize, with_newline: bool, ) -> std::io::Result<usize> { if with_newline { writeln!( out_buffer, "{}", format_args!( "{}{}{}{}{}{}{}", trimmed_line, PLUGIN_ID_SENTINAL, tag, PLUGIN_ID_SENTINAL, ROW_NUMBER_SENTINAL, line_nr, ROW_NUMBER_SENTINAL, ), )?; } else { write!( out_buffer, "{}", format_args!( "{}{}{}{}{}{}{}", trimmed_line, PLUGIN_ID_SENTINAL, tag, PLUGIN_ID_SENTINAL, ROW_NUMBER_SENTINAL, line_nr, ROW_NUMBER_SENTINAL, ), )?; } Ok(trimmed_line.len() + 4 * SENTINAL_LENGTH + tag.len() + linenr_length(line_nr) + 1) } #[inline] pub fn extended_line_length( trimmed_len: usize, tag_len: usize, line_nr: usize, has_newline: bool, ) -> usize { trimmed_len + 4 * SENTINAL_LENGTH + tag_len + linenr_length(line_nr) + if has_newline { 1 } else { 0 } }
#[inline] pub fn next_line_nr(path: &std::path::Path) -> Result<usize, Error> { if !path.exists() { return Ok(0); } let file = fs::File::open(path).expect("opening file did not work"); let file_size = file.metadata().expect("could not read file metadata").len(); if file_size == 0 { return Ok(0); }; let mut reader = BufReader::new(file); let seek_offset: i64 = -(std::cmp::min(file_size - 1, PEEK_END_SIZE as u64) as i64); match reader.seek(SeekFrom::End(seek_offset as i64)) { Ok(_) => (), Err(e) => { return Err(err_msg(format!( "could not read last entry in file {:?}", e ))); } }; let size_of_slice = seek_offset.abs() as usize; let mut buf: Vec<u8> = vec![0; size_of_slice]; reader .read_exact(&mut buf) .expect("reading to buffer should succeed"); for i in 0..size_of_slice - 1 { if buf[i] == (PLUGIN_ID_SENTINAL as u8) && buf[i + 1] == ROW_NUMBER_SENTINAL as u8 { let row_slice = &buf[i + 2..]; let row_string = std::str::from_utf8(row_slice).expect("could not parse row number"); let row_nr: usize = row_string .trim_end_matches(is_newline) .trim_end_matches(ROW_NUMBER_SENTINAL) .parse() .expect("expected number was was none"); return Ok(row_nr + 1); } } Err(err_msg(format!( "did not find row number in line: {:X?}", buf ))) } pub fn get_out_file_and_size( append: bool, out_path: &path::PathBuf, ) -> Result<(fs::File, usize), Error> { let out_file: std::fs::File = if append { std::fs::OpenOptions::new() .append(true) .create(true) .open(out_path)? } else { std::fs::File::create(out_path)? }; let current_out_file_size = out_file.metadata().map(|md| md.len() as usize)?; Ok((out_file, current_out_file_size)) } #[inline] pub fn report_progress( line_nr: usize, current_byte_index: usize, processed_bytes: usize, source_file_size: usize, progress_every_n_lines: usize, ) { if line_nr % progress_every_n_lines == 0 { eprintln!( "processed {} lines -- byte-index {} ({} %)", line_nr, current_byte_index, (processed_bytes as f32 / source_file_size as f32 * 100.0).round() ); } } pub fn get_processed_bytes(append: bool, out: &path::PathBuf) -> u64 { if append { match fs::metadata(out) { Ok(metadata) => metadata.len(), Err(_) => 0, } } else { 0 } }
pub fn linenr_length(linenr: usize) -> usize { if linenr == 0 { return 1; }; let nr = linenr as f64; 1 + nr.log10().floor() as usize }
function_block-full_function
[ { "content": "pub fn read_format_string_options(f: &mut fs::File) -> Result<FormatTestOptions, failure::Error> {\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents)\n\n .expect(\"something went wrong reading the file\");\n\n let v: FormatTestOptions = serde_json::from_str(&...
Rust
src/test_support/mod.rs
housel/ferros
d67a845a76500a84c56031a97feadb181f795d67
use core::marker::PhantomData; use core::ops::Sub; use selfe_sys::*; use typenum::*; use crate::arch::{self, PageBits}; use crate::cap::*; use crate::error::{ErrorExt, SeL4Error}; use crate::pow::{Pow, _Pow}; mod resources; mod types; use crate::vspace::MappedMemoryRegion; pub use resources::*; pub use types::*; impl TestReporter for crate::debug::DebugOutHandle { fn report(&mut self, test_name: &'static str, outcome: TestOutcome) { use core::fmt::Write; let _ = writeln!( self, "test {} ... {}", test_name, if outcome == TestOutcome::Success { "ok" } else { "FAILED" } ); } fn summary(&mut self, passed: u32, failed: u32) { use core::fmt::Write; let _ = writeln!( self, "\ntest result: {}. {} passed; {} failed;", if failed == 0 { "ok" } else { "FAILED" }, passed, failed ); } } pub fn execute_tests<'t, R: types::TestReporter>( mut reporter: R, resources: resources::TestResourceRefs<'t>, tests: &[&types::RunTest], ) -> Result<types::TestOutcome, SeL4Error> { let resources::TestResourceRefs { slots, untyped, asid_pool, mut scratch, mapped_memory_region, cnode, thread_authority, vspace_paging_root, user_image, irq_control, } = resources; let mut successes = 0; let mut failures = 0; for t in tests { with_temporary_resources( slots, untyped, asid_pool, mapped_memory_region, irq_control, |inner_slots, inner_untyped, inner_asid_pool, inner_mapped_memory_region, inner_irq_control| -> Result<(), SeL4Error> { let (name, outcome) = t( inner_slots, inner_untyped, inner_asid_pool, &mut scratch, inner_mapped_memory_region, cnode, thread_authority, vspace_paging_root, user_image, inner_irq_control, ); reporter.report(name, outcome); if outcome == types::TestOutcome::Success { successes += 1; } else { failures += 1; } Ok(()) }, )??; } reporter.summary(successes, failures); Ok(if failures == 0 { types::TestOutcome::Success } else { types::TestOutcome::Failure }) } pub fn with_temporary_resources< SlotCount: Unsigned, UntypedBitSize: Unsigned, MappedBitSize: Unsigned, ASIDPoolSlots: Unsigned, InnerError, Func, >( slots: &mut LocalCNodeSlots<SlotCount>, untyped: &mut LocalCap<Untyped<UntypedBitSize>>, asid_pool: &mut LocalCap<ASIDPool<ASIDPoolSlots>>, mapped_memory_region: &mut MappedMemoryRegion< MappedBitSize, crate::vspace::shared_status::Exclusive, >, irq_control: &mut LocalCap<IRQControl>, f: Func, ) -> Result<Result<(), InnerError>, SeL4Error> where Func: FnOnce( LocalCNodeSlots<SlotCount>, LocalCap<Untyped<UntypedBitSize>>, LocalCap<ASIDPool<arch::ASIDPoolSize>>, MappedMemoryRegion<MappedBitSize, crate::vspace::shared_status::Exclusive>, LocalCap<IRQControl>, ) -> Result<(), InnerError>, MappedBitSize: IsGreaterOrEqual<PageBits>, MappedBitSize: Sub<PageBits>, <MappedBitSize as Sub<PageBits>>::Output: Unsigned, <MappedBitSize as Sub<PageBits>>::Output: _Pow, Pow<<MappedBitSize as Sub<PageBits>>::Output>: Unsigned, { let r = f( Cap::internal_new(slots.cptr, slots.cap_data.offset), Cap { cptr: untyped.cptr, _role: PhantomData, cap_data: Untyped { _bit_size: PhantomData, kind: untyped.cap_data.kind.clone(), }, }, Cap { cptr: asid_pool.cptr, _role: PhantomData, cap_data: ASIDPool { id: asid_pool.cap_data.id, next_free_slot: asid_pool.cap_data.next_free_slot, _free_slots: PhantomData, }, }, unsafe { mapped_memory_region.dangerous_internal_alias() }, Cap { cptr: irq_control.cptr, _role: PhantomData, cap_data: IRQControl { available: irq_control.cap_data.available.clone(), }, }, ); unsafe { slots.revoke_in_reverse() } unsafe { seL4_CNode_Revoke( slots.cptr, untyped.cptr, seL4_WordBits as u8, ) } .as_result() .map_err(|e| SeL4Error::CNodeRevoke(e))?; Ok(r) }
use core::marker::PhantomData; use core::ops::Sub; use selfe_sys::*; use typenum::*; use crate::arch::{self, PageBits}; use crate::cap::*; use crate::error::{ErrorExt, SeL4Error}; use crate::pow::{Pow, _Pow}; mod resources; mod types; use crate::vspace::MappedMemoryRegion; pub use resources::*; pub use types::*; impl TestReporter for crate::debug::DebugOutHandle { fn report(&mut self, test_name: &'static str, outcome: TestOutcome) { use core::fmt::Write; let _ = writeln!( self, "test {} ... {}", test_name, if outcome == TestOutcome::Success { "ok" } else { "FAILED" } ); } fn summary(&mut self, passed: u32, failed: u32) { use core::fmt::Write; let _ = writeln!( self, "\ntest result: {}. {} passed; {} failed;", if failed == 0 { "ok" } else { "FAILED" }, passed, failed ); } } pub fn execute_tests<'t, R: types::TestReporter>( mut reporter: R, resources: resources::TestResourceRefs<'t>, tests:
}, Cap { cptr: irq_control.cptr, _role: PhantomData, cap_data: IRQControl { available: irq_control.cap_data.available.clone(), }, }, ); unsafe { slots.revoke_in_reverse() } unsafe { seL4_CNode_Revoke( slots.cptr, untyped.cptr, seL4_WordBits as u8, ) } .as_result() .map_err(|e| SeL4Error::CNodeRevoke(e))?; Ok(r) }
&[&types::RunTest], ) -> Result<types::TestOutcome, SeL4Error> { let resources::TestResourceRefs { slots, untyped, asid_pool, mut scratch, mapped_memory_region, cnode, thread_authority, vspace_paging_root, user_image, irq_control, } = resources; let mut successes = 0; let mut failures = 0; for t in tests { with_temporary_resources( slots, untyped, asid_pool, mapped_memory_region, irq_control, |inner_slots, inner_untyped, inner_asid_pool, inner_mapped_memory_region, inner_irq_control| -> Result<(), SeL4Error> { let (name, outcome) = t( inner_slots, inner_untyped, inner_asid_pool, &mut scratch, inner_mapped_memory_region, cnode, thread_authority, vspace_paging_root, user_image, inner_irq_control, ); reporter.report(name, outcome); if outcome == types::TestOutcome::Success { successes += 1; } else { failures += 1; } Ok(()) }, )??; } reporter.summary(successes, failures); Ok(if failures == 0 { types::TestOutcome::Success } else { types::TestOutcome::Failure }) } pub fn with_temporary_resources< SlotCount: Unsigned, UntypedBitSize: Unsigned, MappedBitSize: Unsigned, ASIDPoolSlots: Unsigned, InnerError, Func, >( slots: &mut LocalCNodeSlots<SlotCount>, untyped: &mut LocalCap<Untyped<UntypedBitSize>>, asid_pool: &mut LocalCap<ASIDPool<ASIDPoolSlots>>, mapped_memory_region: &mut MappedMemoryRegion< MappedBitSize, crate::vspace::shared_status::Exclusive, >, irq_control: &mut LocalCap<IRQControl>, f: Func, ) -> Result<Result<(), InnerError>, SeL4Error> where Func: FnOnce( LocalCNodeSlots<SlotCount>, LocalCap<Untyped<UntypedBitSize>>, LocalCap<ASIDPool<arch::ASIDPoolSize>>, MappedMemoryRegion<MappedBitSize, crate::vspace::shared_status::Exclusive>, LocalCap<IRQControl>, ) -> Result<(), InnerError>, MappedBitSize: IsGreaterOrEqual<PageBits>, MappedBitSize: Sub<PageBits>, <MappedBitSize as Sub<PageBits>>::Output: Unsigned, <MappedBitSize as Sub<PageBits>>::Output: _Pow, Pow<<MappedBitSize as Sub<PageBits>>::Output>: Unsigned, { let r = f( Cap::internal_new(slots.cptr, slots.cap_data.offset), Cap { cptr: untyped.cptr, _role: PhantomData, cap_data: Untyped { _bit_size: PhantomData, kind: untyped.cap_data.kind.clone(), }, }, Cap { cptr: asid_pool.cptr, _role: PhantomData, cap_data: ASIDPool { id: asid_pool.cap_data.id, next_free_slot: asid_pool.cap_data.next_free_slot, _free_slots: PhantomData, }, }, unsafe { mapped_memory_region.dangerous_internal_alias()
random
[ { "content": "fn gen_id<G: IdGenerator>(g: &mut G, name_hint: &'static str) -> Ident {\n\n syn::Ident::new(&g.gen(name_hint), Span::call_site())\n\n}\n\n\n", "file_path": "ferros-test/test-macro-impl/src/codegen.rs", "rank": 2, "score": 235311.91710156776 }, { "content": "pub fn run(raw_b...
Rust
src/api.rs
FCG-LLC/hyena
5354ed498675aee6ed517c75e13b15849cea5c42
use bincode::{serialize, deserialize, Infinite}; use catalog::{BlockType, Column, PartitionInfo}; use manager::{Manager, BlockCache}; use int_blocks::{Block, Int32SparseBlock, Int64DenseBlock, Int64SparseBlock, Scannable, Deletable, Movable, Upsertable}; use std::time::Instant; use scan::{BlockScanConsumer}; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct InsertMessage { pub row_count : u32, pub col_count : u32, pub col_types : Vec<(u32, BlockType)>, pub blocks : Vec<Block> } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct PartialInsertMessage { pub col_count : u32, pub col_types : Vec<(u32, BlockType)>, pub blocks : Vec<Block> } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct ScanResultMessage { pub row_count : u32, pub col_count : u32, pub col_types : Vec<(u32, BlockType)>, pub blocks : Vec<Block> } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub enum ScanComparison { Lt, LtEq, Eq, GtEq, Gt, NotEq } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct ScanFilter { pub column : u32, pub op : ScanComparison, pub val : u64, pub str_val : Vec<u8> } #[derive(Serialize, Deserialize, PartialEq, Debug)] pub struct ScanRequest { pub min_ts : u64, pub max_ts : u64, pub partition_id : u64, pub projection : Vec<u32>, pub filters : Vec<ScanFilter> } #[derive(Serialize, Deserialize, PartialEq, Debug)] pub struct DataCompactionRequest { pub partition_id : u64, pub filters : Vec<ScanFilter>, pub renamed_columns: Vec<(u32, u32)>, pub dropped_columns: Vec<u32>, pub upserted_data: PartialInsertMessage } #[derive(Serialize, Deserialize, PartialEq, Debug)] pub struct RefreshCatalogResponse { pub columns: Vec<Column>, pub available_partitions: Vec<PartitionInfo> } #[derive(Serialize, Deserialize, PartialEq, Debug)] pub struct AddColumnRequest { pub column_name: String, pub column_type: BlockType } #[derive(Serialize, Deserialize, PartialEq, Debug)] pub struct GenericResponse { pub status : u32 } impl GenericResponse { pub fn create_as_buf(status : u32) -> Vec<u8> { let resp = GenericResponse { status: status }; serialize(&resp, Infinite).unwrap() } } #[derive(Serialize, Deserialize, PartialEq, Debug)] pub enum ApiOperation { Insert, Scan, RefreshCatalog, AddColumn, Flush, DataCompaction } #[derive(Serialize, Deserialize, PartialEq, Debug)] pub struct ApiMessage { pub op_type : ApiOperation, pub payload : Vec<u8> } impl ApiMessage { pub fn extract_scan_request(&self) -> ScanRequest { assert_eq!(self.op_type, ApiOperation::Scan); let scan_request = deserialize(&self.payload[..]).unwrap(); scan_request } pub fn extract_insert_message(&self) -> InsertMessage { assert_eq!(self.op_type, ApiOperation::Insert); let insert_message = deserialize(&self.payload[..]).unwrap(); insert_message } pub fn extract_data_compaction_request(&self) -> DataCompactionRequest { assert_eq!(self.op_type, ApiOperation::DataCompaction); let compaction_request = deserialize(&self.payload[..]).unwrap(); compaction_request } pub fn extract_add_column_message(&self) -> AddColumnRequest { assert_eq!(self.op_type, ApiOperation::AddColumn); let column_message = deserialize(&self.payload[..]).unwrap(); column_message } } impl ScanResultMessage { pub fn new() -> ScanResultMessage { ScanResultMessage { row_count: 0, col_count: 0, col_types: Vec::new(), blocks: Vec::new() } } } impl RefreshCatalogResponse { pub fn new(manager: &Manager) -> RefreshCatalogResponse { RefreshCatalogResponse { columns: manager.catalog.columns.to_owned(), available_partitions: manager.catalog.available_partitions.to_owned() } } } fn consume_empty_filter<'a>(manager : &Manager, cache : &'a mut BlockCache, consumer : &mut BlockScanConsumer) { let scanned_block = manager.load_block(&cache.partition_info, 0); match &scanned_block { &Block::Int64Dense(ref x) => { for i in 0..x.data.len() { consumer.matching_offsets.push(i as u32); } }, _ => println!("This is unexpected - TS is not here") } cache.cache_block(scanned_block, 0); } fn consume_filters<'a>(manager : &'a Manager, cache: &'a mut BlockCache, filter: &'a ScanFilter, mut consumer: &mut BlockScanConsumer) { let scanned_block = manager.load_block(&cache.partition_info, filter.column); match &scanned_block { &Block::StringBlock(ref x) => { let str_value:String = String::from_utf8(filter.str_val.to_owned()).unwrap(); scanned_block.scan(filter.op.clone(), &str_value, &mut consumer) }, _ => scanned_block.scan(filter.op.clone(), &filter.val, &mut consumer) } cache.cache_block(scanned_block, filter.column); } fn part_scan_and_combine(manager: &Manager, part_info : &PartitionInfo, mut cache : &mut BlockCache, req : &ScanRequest) -> BlockScanConsumer { let mut consumers:Vec<BlockScanConsumer> = Vec::new(); if req.filters.is_empty() { let mut consumer = BlockScanConsumer{matching_offsets : Vec::new()}; consume_empty_filter(manager, &mut cache, &mut consumer); consumers.push(consumer); } else { for filter in &req.filters { let mut consumer = BlockScanConsumer{matching_offsets : Vec::new()}; consume_filters(manager, &mut cache, &filter, &mut consumer); consumers.push(consumer); } } BlockScanConsumer::merge_and_scans(&consumers) } pub fn handle_data_compaction(manager: &Manager, req : &DataCompactionRequest) { let part_info = &manager.find_partition_info(req.partition_id); let mut cache = BlockCache::new(part_info); let scan_req = ScanRequest { min_ts: 0, max_ts: u64::max_value(), partition_id: req.partition_id, filters: req.filters.to_owned(), projection: vec![] }; let combined_consumer = part_scan_and_combine(manager, part_info, &mut cache, &scan_req); for col in &req.dropped_columns { let mut cur = manager.load_block(part_info, *col); cur.delete(&combined_consumer.matching_offsets); manager.save_block(part_info, &cur, *col); } for col_pair in &req.renamed_columns { let mut c0 = manager.load_block(part_info, col_pair.0); let mut c1 = manager.load_block(part_info, col_pair.1); c0.move_data(&mut c1, &combined_consumer); manager.save_block(part_info, &c0, col_pair.0); manager.save_block(part_info, &c1, col_pair.1); } for col_no in 0..req.upserted_data.col_count { let catalog_col_no = req.upserted_data.col_types[col_no as usize].0; let mut block = manager.load_block(part_info, catalog_col_no); let input_block = &req.upserted_data.blocks[col_no as usize]; if input_block.len() != 1 { panic!("The upsert block can have only one record which is copied across all matching entries"); } match &mut block { &mut Block::StringBlock(ref mut b) => match input_block { &Block::StringBlock(ref c) => b.multi_upsert(&combined_consumer.matching_offsets, c.str_data.as_slice()), _ => panic!("Non matching block types") }, &mut Block::Int64Sparse(ref mut b) => match input_block { &Block::Int64Sparse(ref c) => b.multi_upsert(&combined_consumer.matching_offsets, c.data[0].1), _ => panic!("Non matching block types") }, &mut Block::Int32Sparse(ref mut b) => match input_block { &Block::Int32Sparse(ref c) => b.multi_upsert(&combined_consumer.matching_offsets, c.data[0].1), _ => panic!("Non matching block types") }, &mut Block::Int16Sparse(ref mut b) => match input_block { &Block::Int16Sparse(ref c) => b.multi_upsert(&combined_consumer.matching_offsets, c.data[0].1), _ => panic!("Non matching block types") }, &mut Block::Int8Sparse(ref mut b) => match input_block { &Block::Int8Sparse(ref c) => b.multi_upsert(&combined_consumer.matching_offsets, c.data[0].1), _ => panic!("Non matching block types") }, _ => panic!("Not supported block type") } manager.save_block(part_info, &block, catalog_col_no); } } pub fn part_scan_and_materialize(manager: &Manager, req : &ScanRequest) -> ScanResultMessage { let scan_duration = Instant::now(); let part_info = &manager.find_partition_info(req.partition_id); let mut cache = BlockCache::new(part_info); let combined_consumer = part_scan_and_combine(manager, part_info, &mut cache, req); let mut scan_msg = ScanResultMessage::new(); combined_consumer.materialize(&manager, &mut cache, &req.projection, &mut scan_msg); let total_matched = combined_consumer.matching_offsets.len(); let total_materialized = scan_msg.row_count; println!("Scanning and matching/materializing {}/{} elements took {:?}", total_matched, total_materialized, scan_duration.elapsed()); scan_msg } #[test] fn string_filters() { let input_str_val_bytes:Vec<u8> = vec![84, 101]; let filter_val:String = String::from_utf8(input_str_val_bytes).unwrap(); assert_eq!("Te", filter_val); } #[test] fn data_compaction_test() { } #[test] fn inserting_works() { let mut test_msg:Vec<u8> = vec![]; let base_ts = 1495490000 * 1000000; let insert_msg = InsertMessage { row_count: 3, col_count: 5, col_types: vec![(0, BlockType::Int64Dense), (1, BlockType::Int64Dense), (2, BlockType::Int64Sparse), (4, BlockType::Int64Sparse)], blocks: vec![ Block::Int64Dense(Int64DenseBlock{ data: vec![base_ts, base_ts+1000, base_ts+2000] }), Block::Int64Dense(Int64DenseBlock{ data: vec![0, 0, 1, 2] }), Block::Int64Sparse(Int64SparseBlock{ data: vec![(0, 100), (1, 200)] }), Block::Int64Sparse(Int64SparseBlock{ data: vec![(2, 300), (3, 400)] }), ] }; test_msg.extend(serialize(&insert_msg, Infinite).unwrap()); println!("In test {:?}", test_msg); } #[test] fn api_scan_message_serialization() { let scan_req = ScanRequest { min_ts: 100 as u64, max_ts: 200 as u64, partition_id: 0, filters: vec![ ScanFilter { column: 5, op: ScanComparison::GtEq, val: 1000 as u64, str_val: vec![] } ], projection: vec![0,1,2,3] }; let api_msg = ApiMessage { op_type: ApiOperation::Scan, payload: serialize(&scan_req, Infinite).unwrap() }; let serialized_msg = serialize(&api_msg, Infinite).unwrap(); println!("Filter #1: {:?}", serialize(&scan_req.filters[0], Infinite).unwrap()); println!("Filters: {:?}", serialize(&scan_req.filters, Infinite).unwrap()); println!("Projection: {:?}", serialize(&scan_req.projection, Infinite).unwrap()); println!("Scan request: {:?}", serialize(&scan_req, Infinite).unwrap()); println!("Payload length: {}", api_msg.payload.len()); println!("Serialized api message for scan: {:?}", serialized_msg); } #[test] fn api_refresh_catalog_serialization() { let pseudo_response = RefreshCatalogResponse{ columns: vec![ Column { data_type: BlockType::Int64Dense, name: String::from("ts") }, Column { data_type: BlockType::Int32Sparse, name: String::from("source") } ], available_partitions: vec![ PartitionInfo{ min_ts: 100, max_ts: 200, id: 999, location: String::from("/foo/bar") } ] }; let x:String = String::from("abc"); println!("String response: {:?}", serialize(&x, Infinite).unwrap()); println!("Pseudo catalog refresh response: {:?}", serialize(&pseudo_response, Infinite).unwrap()); }
use bincode::{serialize, deserialize, Infinite}; use catalog::{BlockType, Column, PartitionInfo}; use manager::{Manager, BlockCache}; use int_blocks::{Block, Int32SparseBlock, Int64DenseBlock, Int64SparseBlock, Scannable, Deletable, Movable, Upsertable}; use std::time::Instant; use scan::{BlockScanConsumer}; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct InsertMessage { pub row_count : u32, pub col_count : u32, pub col_types : Vec<(u32, BlockType)>, pub blocks : Vec<Block> } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct PartialInsertMessage { pub col_count : u32, pub col_types : Vec<(u32, BlockType)>, pub blocks : Vec<Block> } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct ScanResultMessage { pub row_count : u32, pub col_count : u32, pub col_types : Vec<(u32, BlockType)>, pub blocks : Vec<Block> } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub enum ScanComparison { Lt, LtEq, Eq, GtEq, Gt, NotEq } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct ScanFilter { pub column : u32, pub op : ScanComparison, pub val : u64, pub str_val : Vec<u8> } #[derive(Serialize, Deserialize, PartialEq, Debug)] pub struct ScanRequest { pub min_ts : u64, pub max_ts : u64, pub partition_id : u64, pub projection : Vec<u32>, pub filters : Vec<ScanFilter> } #[derive(Serialize, Deserialize, PartialEq, Debug)] pub struct DataCompactionRequest { pub partition_id : u64, pub filters : Vec<ScanFilter>, pub renamed_columns: Vec<(u32, u32)>, pub dropped_columns: Vec<u32>, pub upserted_data: PartialInsertMessage } #[derive(Serialize, Deserialize, PartialEq, Debug)] pub struct RefreshCatalogResponse { pub columns: Vec<Column>, pub available_partitions: Vec<PartitionInfo> } #[derive(Serialize, Deserialize, PartialEq, Debug)] pub struct AddColumnRequest { pub column_name: String, pub column_type: BlockType } #[derive(Serialize, Deserialize, PartialEq, Debug)] pub struct GenericResponse { pub status : u32 } impl GenericResponse { pub fn create_as_buf(status : u32) -> Vec<u8> { let resp = GenericResponse { status: status }; serialize(&resp, Infinite).unwrap() } } #[derive(Serialize, Deserialize, PartialEq, Debug)] pub enum ApiOperation { Insert, Scan, RefreshCatalog, AddColumn, Flush, DataCompaction } #[derive(Serialize, Deserialize, PartialEq, Debug)] pub struct ApiMessage { pub op_type : ApiOperation, pub payload : Vec<u8> } impl ApiMessage { pub fn extract_scan_request(&self) -> ScanRequest { assert_eq!(self.op_type, ApiOperation::Scan); let scan_request = deserialize(&self.payload[..]).unwrap(); scan_request } pub fn extract_insert_message(&self) -> InsertMessage { assert_eq!(self.op_type, ApiOperation::Insert); let insert_message = deserialize(&self.payload[..]).unwrap(); insert_message } pub fn extract_data_compaction_request(&self) -> DataCompactionRequest { assert_eq!(self.op_type, ApiOperation::DataCompaction); let compaction_request = deserialize(&self.payload[..]).unwrap(); compaction_request } pub fn extract_add_column_message(&self) -> AddColumnRequest { assert_eq!(self.op_type, ApiOperation::AddColumn); let column_message = deserialize(&self.payload[..]).unwrap(); column_message } } impl ScanResultMessage { pub fn new() -> ScanResultMessage { ScanResultMessage { row_count: 0, col_count: 0, col_types: Vec::new(), blocks: Vec::new() } } } impl RefreshCatalogResponse { pub fn new(manager: &Manager) -> RefreshCatalogResponse { RefreshCatalogResponse { columns: manager.catalog.columns.to_owned(), available_partitions: manager.catalog.available_partitions.to_owned() } } } fn consume_empty_filter<'a>(manager : &Manager, cache : &'a mut BlockCache, consumer : &mut BlockScanConsumer) { let scanned_block = manager.load_block(&cache.partition_info, 0); match &scanned_block { &Block::Int64Dense(ref x) => { for i in 0..x.data.len() { consumer.matching_offsets.push(i as u32); } }, _ => println!("This is unexpected - TS is not here") } cache.cache_block(scanned_block, 0); } fn consume_filters<'a>(manager : &'a Manager, cache: &'a mut BlockCache, filter: &'a ScanFilter, mut consumer: &mut BlockScanConsumer) { let scanned_block = manager.load_block(&cache.partition_info, filter.column); match &scanned_block { &Block::StringBlock(ref x) => { let str_value:String = String::from_utf8(filter.str_val.to_owned()).unwrap(); scanned_block.scan(filter.op.clone(), &str_value, &mut consumer) }, _ => scanned_block.scan(filter.op.clone(), &filter.val, &mut consumer) } cache.cache_block(scanned_block, filter.column); } fn part_scan_and_combine(manager: &Manager, part_info : &PartitionInfo, mut cache : &mut BlockCache, req : &ScanRequest) -> BlockScanConsumer { let mut consumers:Vec<BlockScanConsumer> = Vec::new(); if req.filters.is_empty() { let mut consumer = BlockScanConsumer{matching_offsets : Vec::new()}; consume_empty_filter(manager, &mut cache, &mut consumer); consumers.push(consumer); } else { for filter in &req.filters { let mut consumer = BlockScanConsumer{matching_offsets : Vec::new()}; consume_filters(manager, &mut cache, &filter, &mut consumer); consumers.push(consumer); } } BlockScanConsumer::merge_and_scans(&consumers) } pub fn handle_data_compaction(manager: &Manager, req : &DataCompactionRequest) { let part_info = &manager.find_partition_info(req.partition_id); let mut cache = BlockCache::new(part_info); let scan_req = ScanRequest { min_ts: 0, max_ts: u64::max_value(), partition_id: req.partition_id, filters: req.filters.to_owned(), projection: vec![] }; let combined_consumer = part_scan_and_combine(manager, part_info, &mut cache, &scan_req); for col in &req.dropped_columns { let mut cur = manager.load_block(part_info, *col); cur.delete(&combined_consumer.matching_offsets); manager.save_block(part_info, &cur, *col); } for col_pair in &req.renamed_columns { let mut c0 = manager.load_block(part_info, col_pair.0); let mut c1 = manager.load_block(part_info, col_pair.1); c0.move_data(&mut c1, &combined_consumer); manager.save_block(part_info, &c0, col_pair.0); manager.save_block(part_info, &c1, col_pair.1); } for col_no in 0..req.upserted_data.col_count { let catalog_col_no = req.upserted_data.col_types[col_no as usize].0; let mut block = manager.load_block(part_info, catalog_col_no); let input_block = &req.upserted_data.blocks[col_no as usize]; if input_block.len() != 1 { panic!("The upsert block can have only one record which is copied across all matching entries"); } match &mut block { &mut Block::StringBlock(ref mut b) => match input_block { &Block::StringBlock(ref c) => b.multi_upsert(&combined_consumer.matching_offsets, c.str_data.as_slice()), _ => panic!("Non matching block types") }, &mut Block::Int64Sparse(ref mut b) => match input_block { &Block::Int64Sparse(ref c) => b.multi_upsert(&combined_consumer.matching_offsets, c.data[0].1), _ => panic!("Non matching block types") }, &mut Block::Int32Sparse(ref mut b) => match input_block { &Block::Int32Sparse(ref c) => b.multi_upsert(&combined_consumer.matching_offsets, c.data[0].1), _ => panic!("Non matching block types") }, &mut Block::Int16Sparse(ref mut b) => match input_block { &Block::Int16Sparse(ref c) => b.multi_upsert(&combined_consumer.matching_offsets, c.data[0].1), _ => panic!("Non matching block types") }, &mut Block::Int8Sparse(ref mut b) => match input_block { &Block::Int8Sparse(ref c) => b.multi_upsert(&combined_consumer.matching_offsets, c.data[0].1), _ => panic!("Non matching block types") }, _ => panic!("Not supported block type") } manager.save_block(part_info, &block, catalog_col_no); } } pub fn part_scan_and_materialize(manager: &Manager, req : &ScanRequest) -> ScanResultMessage { let scan_duration = Instant::now(); let part_info = &manager.find_partition_info(req.partition_id); let mut cache = BlockCache::new(part_info); let combined_consumer = part_scan_and_combine(manager, part_info, &mut cache, req); let mut scan_msg = ScanResultMessage::new(); combined_consumer.materialize(&manager, &mut cache, &req.projection, &mut scan_msg); let total_matched = combined_consumer.matching_offsets.len(); let total_materialized = scan_msg.row_count; println!("Scanning and matching/materializing {}/{} elements took {:?}", total_matched, total_materialized, scan_duration.elapsed()); scan_msg } #[test] fn string_filters() { let input_str_val_bytes:Vec<u8> = vec![84, 101]; let filter_val:String = String::from_utf8(input_str_val_bytes).unwrap(); assert_eq!("Te", filter_val); } #[test] fn data_compaction_test() { } #[test] fn inserting_works() { let mut test_msg:Vec<u8> = vec![]; let base_ts = 1495490000 * 1000000; let insert_msg = InsertMessage { row_count: 3, col_count: 5, col_types: vec![(0, BlockType::Int64Dense), (1, BlockType::Int64Dense), (2, BlockType::Int64Sparse), (4, BlockType::Int64Sparse)], blocks: vec![ Block::Int64Dense(Int64DenseBlock{ data: vec![base_ts, base_ts+1000, base_ts+2000] }), Block::Int64Dense(Int64DenseBlock{ data: vec![0, 0, 1, 2] }), Block::Int64Sparse(Int64SparseBlock{ data: vec![(0, 100), (1, 200)] }), Block::Int64Sparse(Int64SparseBlock{ data: vec![(2, 300), (3, 400)] }), ] }; test_msg.extend(serialize(&insert_msg, Infinite).unwrap()); println!("In test {:?}", test_msg); } #[test] fn api_scan_message_serialization() { let scan_req = ScanRequest { min_ts: 100 as u64, max_ts: 200 as u64, partition_id: 0, filters: vec![ ScanFilter { column: 5, op: ScanComparison::GtEq, val: 1000 as u64, str_val: vec![] } ], projection: vec![0,1,2,3] }; let api_msg = ApiMessage { op_type: ApiOperation::Scan, payload: serialize(&scan_req, Infinite).unwrap() }; let serialized_msg = serialize(&api_msg, Infinite).unwrap(); println!("Filter #1: {:?}", serialize(&scan_req.filters[0], Infinite).unwrap()); println!("Filters: {:?}", serialize(&scan_req.filters, Infinite).unwrap()); println!("Projection: {:?}", serialize(&scan_req.projection, Infinite).unwrap()); println!("Scan request: {:?}", serialize(&scan_req, Infinite).unwrap()); println!("Payload length: {}", api_msg.payload.len()); println!("Serialized api message for scan: {:?}", serialized_msg); } #[test] fn api_refresh_catalog_serialization() { let pseudo_response = RefreshCatalogResponse{ columns: vec![ Column { data_type: BlockType::Int64Dense, name: String
rialize(&x, Infinite).unwrap()); println!("Pseudo catalog refresh response: {:?}", serialize(&pseudo_response, Infinite).unwrap()); }
::from("ts") }, Column { data_type: BlockType::Int32Sparse, name: String::from("source") } ], available_partitions: vec![ PartitionInfo{ min_ts: 100, max_ts: 200, id: 999, location: String::from("/foo/bar") } ] }; let x:String = String::from("abc"); println!("String response: {:?}", se
random
[ { "content": "fn create_message(ts_base : u64) -> InsertMessage {\n\n let mut rng = rand::thread_rng();\n\n\n\n let mut pseudo_ts = ts_base * 1000000;\n\n\n\n let mut blocks : Vec<Block> = Vec::new();\n\n let mut col_types : Vec<(u32, BlockType)> = Vec::new();\n\n\n\n for col_no in 0..2 + TEST_CO...
Rust
src/models/repository.rs
QaQAdrian/git-tui
02c32a972055c695c3ad6465daf72c12913568d1
use std::collections::HashMap; use std::fs; use std::fs::{File, OpenOptions}; use std::io::Write; use std::path::Path; use git2::Repository; use crate::ui::message::{Level, MessageView}; static FILE_STR: &str = "/git-tui.log"; pub struct Repositories { pub search_path: String, pub map: HashMap<String, Repository>, pub log_file: Option<File>, } impl Repositories { pub fn init(path: String, _recursive: bool, _depth: Option<u32>) -> Repositories { let file_path = format!("{}{}", path, FILE_STR); let file = OpenOptions::new() .write(true) .append(true) .create(true) .open(file_path) .ok(); let mut repos = Repositories { map: HashMap::new(), search_path: path, log_file: file, }; if let Err(e) = repos.add_repo_recursive(repos.search_path.clone()) { println!("Recursive Error:{}", e); } repos } fn add_repo_recursive(&mut self, parent_path: impl AsRef<Path>) -> Result<(), std::io::Error> { for entry in fs::read_dir(parent_path)? { let entry = entry?; let data = entry.metadata()?; let path = entry.path(); if data.is_dir() { if self.add_repo(path.to_str().unwrap().to_string()).is_ok() { continue; } else { if let Err(e) = self.add_repo_recursive(&path) { println!("Add Repo Error:{}", e); } } } } Ok(()) } pub fn refresh(&mut self) { self.clear(); if let Err(e) = self.add_repo_recursive(self.search_path.clone()) { println!("Recursive Error:{}", e); } } pub fn repos_info(&self) -> Vec<(String, String)> { let mut vec = vec![]; for (path, repo) in &self.map { let s = path.clone(); let local_branch = repo.head().unwrap(); let local_branch = local_branch.name().unwrap(); vec.push((s, local_branch.to_string())); } vec } pub fn execute<F>(&self, repo_key: Option<String>, command: &String, closure: &mut F, view: &mut Box<MessageView>) where F: FnMut(String, Level, &mut Box<MessageView>), { let command = command.trim(); if command.len() == 0 { return; } let mut error_num = 0; let is_none = repo_key.is_none(); let key = repo_key.unwrap_or("".to_string()); if let Some(_f) = &self.log_file { closure(format!("More detail : {}{}", self.search_path, FILE_STR), Level::INFO, view); } for (relative_path, repo) in &self.map { if is_none || relative_path.eq(&key) { let path = repo.path(); let mut cmd = command.to_string(); if let Some(position) = command.find("git") { cmd.insert_str( position + 3, format!(" {}{} ", "--git-dir=", path.display()).as_str(), ) } let (code, output, error) = run_script!(cmd).unwrap(); if code == 0 { closure(format!("OK! repo: {}", relative_path), Level::INFO, view); if !is_none { closure(format!("info: {}", output), Level::INFO, view); } } else { error_num += 1; let mut error_info = format!("CMD: {} , ERROR: {}", cmd, error); closure(error_info.clone(), Level::ERROR, view); error_info.push('\n'); self.log(format!("code:{} output: {} error: {}", code, output, error)); } } } if error_num > 0 { closure(format!("Error Num: {}", error_num), Level::INFO, view); } } fn log(&self, s: String) { self.log_file.as_ref().map(|mut f| { if let Err(e) = f.write(s.as_bytes()) { eprintln!("Write log file Error {}", e); } }); } fn add_repo(&mut self, path: String) -> Result<(), git2::Error> { let repo = Repository::discover(&path)?; let s = path.split_at(self.search_path.len()).1; self.map.insert(s.to_string(), repo); Ok(()) } fn clear(&mut self) { self.map.clear(); } } #[test] fn test() {}
use std::collections::HashMap; use std::fs; use std::fs::{File, OpenOptions}; use std::io::Write; use std::path::Path; use git2::Repository; use crate::ui::message::{Level, MessageView}; static FILE_STR: &str = "/git-tui.log"; pub struct Repositories { pub search_path: String, pub map: HashMap<String, Repository>, pub log_file: Option<File>, } impl Repositories { pub fn init(path: String, _recursive: bool, _depth: Option<u32>) -> Repositories { let file_path = format!("{}{}", path, FILE_STR); let file = OpenOptions::new() .write(true) .append(true) .create(true) .open(file_path) .ok(); let mut repos = Repositories { map: HashMap::new(), search_path: path, log_file: file, }; if let Err(e) = repos.add_repo_recursive(repos.search_path.clone()) { println!("Recursive Error:{}", e); } repos } fn add_repo_recursive(&mut self, parent_path: impl AsRef<Path>) -> Result<(), std::io::Error> { for entry in fs::read_dir(parent_path)? { let entry = entry?; let data = entry.metadata()?; let path = entry.path(); if data.is_dir() { if self.add_repo(path.to_str().unwrap().to_string()).is_ok() { continue; } else { if let Err(e) = self.add_repo_recursive(&path) { println!("Add Repo Error:{}", e); } } } } Ok(()) } pub fn refresh(&mut self) { self.clear(); if let Err(e) = self.add_repo_recursive(self.search_path.clone()) { println!("Recursive Error:{}", e); } } pub fn repos_info(&self) -> Vec<(String, String)> { let mut vec = vec![]; for (path, repo) in &self.map { let s = path.clone(); let local_branch = repo.head().unwrap(); let local_branch = local_branch.name().unwrap(); vec.push((s, local_branch.to_string())); } vec } pub fn execute<F>(&self, repo_key: Option<String>, command: &String, closure: &mut F, view: &mut Box<MessageView>) where F: FnMut(String, Level, &mut Box<MessageView>), { let command = command.trim(); if command.len() == 0 { return; } let mut error_num = 0; let is_none = repo_key.is_none(); let key = repo_key.unwrap_or("".to_string()); if let Some(_f) = &self.log_file { closure(format!("More detail : {}{}", self.search_path, FILE_STR), Level::INFO, view); } for (relative_path, repo) in &self.map { if is_none || relative_path.eq(&key) { let path = repo.path(); let mut cmd = command.to_string(); if let Some(position) = command.find("git") { cmd.insert_str(
fn log(&self, s: String) { self.log_file.as_ref().map(|mut f| { if let Err(e) = f.write(s.as_bytes()) { eprintln!("Write log file Error {}", e); } }); } fn add_repo(&mut self, path: String) -> Result<(), git2::Error> { let repo = Repository::discover(&path)?; let s = path.split_at(self.search_path.len()).1; self.map.insert(s.to_string(), repo); Ok(()) } fn clear(&mut self) { self.map.clear(); } } #[test] fn test() {}
position + 3, format!(" {}{} ", "--git-dir=", path.display()).as_str(), ) } let (code, output, error) = run_script!(cmd).unwrap(); if code == 0 { closure(format!("OK! repo: {}", relative_path), Level::INFO, view); if !is_none { closure(format!("info: {}", output), Level::INFO, view); } } else { error_num += 1; let mut error_info = format!("CMD: {} , ERROR: {}", cmd, error); closure(error_info.clone(), Level::ERROR, view); error_info.push('\n'); self.log(format!("code:{} output: {} error: {}", code, output, error)); } } } if error_num > 0 { closure(format!("Error Num: {}", error_num), Level::INFO, view); } }
function_block-function_prefix_line
[]
Rust
carbide_controls/src/radio_button.rs
HolgerGottChristensen/carbide
dda3c0426b8c6a9001eadb16ab0b2369e26ed1be
use std::fmt::Debug; use carbide_core::{DeserializeOwned, Serialize}; use carbide_core::draw::Dimension; use carbide_core::widget::*; use crate::PlainRadioButton; #[derive(Clone, Widget)] pub struct RadioButton<T, GS> where GS: GlobalStateContract, T: Serialize + Clone + Debug + Default + DeserializeOwned + PartialEq + 'static, { id: Id, child: PlainRadioButton<T, GS>, position: Point, dimension: Dimensions, } impl< T: Serialize + Clone + Debug + Default + DeserializeOwned + PartialEq + 'static, GS: GlobalStateContract, > RadioButton<T, GS> { pub fn new<S: Into<StringState<GS>>, L: Into<TState<T, GS>>>( label: S, reference: T, local_state: L, ) -> Box<Self> { let mut child = *PlainRadioButton::new(label, reference, local_state); child = *child.delegate(|focus_state, selected_state, button: Box<dyn Widget<GS>>| { let focus_color = TupleState3::new( focus_state, EnvironmentColor::OpaqueSeparator, EnvironmentColor::Accent, ) .mapped(|(focus, primary_color, focus_color)| { if focus == &Focus::Focused { *focus_color } else { *primary_color } }); let selected_color = TupleState3::new( selected_state.clone(), EnvironmentColor::SecondarySystemBackground, EnvironmentColor::Accent, ) .mapped(|(selected, primary_color, selected_color)| { if *selected { *selected_color } else { *primary_color } }); ZStack::new(vec![ Ellipse::new() .fill(selected_color) .stroke(focus_color) .stroke_style(1.0), IfElse::new(selected_state).when_true( Ellipse::new() .fill(EnvironmentColor::DarkText) .frame(6.0, 6.0), ), button, ]) .frame(16.0, 16.0) }); Box::new(RadioButton { id: Id::new_v4(), child, position: [0.0, 0.0], dimension: [235.0, 26.0], }) } } impl< T: Serialize + Clone + Debug + Default + DeserializeOwned + PartialEq + 'static, GS: GlobalStateContract, > CommonWidget<GS> for RadioButton<T, GS> { fn id(&self) -> Id { self.id } fn set_id(&mut self, id: Id) { self.id = id; } fn flag(&self) -> Flags { Flags::EMPTY } fn children(&self) -> WidgetIter { WidgetIter::single(&self.child) } fn children_mut(&mut self) -> WidgetIterMut { WidgetIterMut::single(&mut self.child) } fn proxied_children(&mut self) -> WidgetIterMut { WidgetIterMut::single(&mut self.child) } fn proxied_children_rev(&mut self) -> WidgetIterMut { WidgetIterMut::single(&mut self.child) } fn position(&self) -> Point { self.position } fn set_position(&mut self, position: Dimensions) { self.position = position; } fn dimension(&self) -> Dimensions { self.dimension } fn set_dimension(&mut self, dimension: Dimension) { self.dimension = dimension } } impl< T: Serialize + Clone + Debug + Default + DeserializeOwned + PartialEq + 'static, GS: GlobalStateContract, > ChildRender for RadioButton<T, GS> {} impl< T: Serialize + Clone + Debug + Default + DeserializeOwned + PartialEq + 'static, GS: GlobalStateContract, > Layout<GS> for RadioButton<T, GS> { fn flexibility(&self) -> u32 { 5 } fn calculate_size(&mut self, requested_size: Dimensions, env: &mut Environment) -> Dimensions { self.set_width(requested_size[0]); self.child.calculate_size(self.dimension, env); self.dimension } fn position_children(&mut self) { let positioning = BasicLayouter::Center.position(); let position = self.position(); let dimension = self.dimension(); positioning(position, dimension, &mut self.child); self.child.position_children(); } } impl< T: Serialize + Clone + Debug + Default + DeserializeOwned + PartialEq + 'static, GS: GlobalStateContract, > WidgetExt<GS> for RadioButton<T, GS> {}
use std::fmt::Debug; use carbide_core::{DeserializeOwned, Serialize}; use carbide_core::draw::Dimension; use carbide_core::widget::*; use crate::PlainRadioButton; #[derive(Clone, Widget)] pub struct RadioButton<T, GS> where GS: GlobalStateContract, T: Serialize + Clone + Debug + Default + DeserializeOwned + PartialEq + 'static, { id: Id, child: PlainRadioButton<T, GS>, position: Point, dimension: Dimensions, } impl< T: Serialize + Clone + Debug + Default + DeserializeOwned + PartialEq + 'static, GS: GlobalStateContract, > RadioButton<T, GS> { pub fn new<S: Into<StringState<GS>>, L: Into<TState<T, GS>>>( label: S, reference: T, local_state: L, ) -> Box<Self> { let mut child = *PlainRadioButton::new(label, reference, local_state); child = *child.delegate(|focus_state, selected_state, button: Box<dyn Widget<GS>>| { let focus_color = TupleState3::new( focus_state, EnvironmentColor::OpaqueSeparator, EnvironmentColor::Accent, ) .mapped(|(focus, primary_color, focus_color)| { if focus == &Focus::Focused { *focus_color } else { *primary_color } }); let selected_color = TupleState3::new( selected_state.clone(), EnvironmentColor::SecondarySystemBackgrou
atic, GS: GlobalStateContract, > CommonWidget<GS> for RadioButton<T, GS> { fn id(&self) -> Id { self.id } fn set_id(&mut self, id: Id) { self.id = id; } fn flag(&self) -> Flags { Flags::EMPTY } fn children(&self) -> WidgetIter { WidgetIter::single(&self.child) } fn children_mut(&mut self) -> WidgetIterMut { WidgetIterMut::single(&mut self.child) } fn proxied_children(&mut self) -> WidgetIterMut { WidgetIterMut::single(&mut self.child) } fn proxied_children_rev(&mut self) -> WidgetIterMut { WidgetIterMut::single(&mut self.child) } fn position(&self) -> Point { self.position } fn set_position(&mut self, position: Dimensions) { self.position = position; } fn dimension(&self) -> Dimensions { self.dimension } fn set_dimension(&mut self, dimension: Dimension) { self.dimension = dimension } } impl< T: Serialize + Clone + Debug + Default + DeserializeOwned + PartialEq + 'static, GS: GlobalStateContract, > ChildRender for RadioButton<T, GS> {} impl< T: Serialize + Clone + Debug + Default + DeserializeOwned + PartialEq + 'static, GS: GlobalStateContract, > Layout<GS> for RadioButton<T, GS> { fn flexibility(&self) -> u32 { 5 } fn calculate_size(&mut self, requested_size: Dimensions, env: &mut Environment) -> Dimensions { self.set_width(requested_size[0]); self.child.calculate_size(self.dimension, env); self.dimension } fn position_children(&mut self) { let positioning = BasicLayouter::Center.position(); let position = self.position(); let dimension = self.dimension(); positioning(position, dimension, &mut self.child); self.child.position_children(); } } impl< T: Serialize + Clone + Debug + Default + DeserializeOwned + PartialEq + 'static, GS: GlobalStateContract, > WidgetExt<GS> for RadioButton<T, GS> {}
nd, EnvironmentColor::Accent, ) .mapped(|(selected, primary_color, selected_color)| { if *selected { *selected_color } else { *primary_color } }); ZStack::new(vec![ Ellipse::new() .fill(selected_color) .stroke(focus_color) .stroke_style(1.0), IfElse::new(selected_state).when_true( Ellipse::new() .fill(EnvironmentColor::DarkText) .frame(6.0, 6.0), ), button, ]) .frame(16.0, 16.0) }); Box::new(RadioButton { id: Id::new_v4(), child, position: [0.0, 0.0], dimension: [235.0, 26.0], }) } } impl< T: Serialize + Clone + Debug + Default + DeserializeOwned + PartialEq + 'st
random
[ { "content": "fn bordered_rectangle(button_id: widget::Id, rectangle_id: widget::Id,\n\n rect: Rect, color: Color, style: &Style, ui: &mut UiCell)\n\n{\n\n // BorderedRectangle widget.\n\n let dim = rect.dim();\n\n let border = style.border(&ui.theme);\n\n let border_color = sty...
Rust
src/live_consumer.rs
sevenEng/kafka-view
6dfb045117ed5f0f571ccb7e8e7f99f1950ffc95
use rdkafka::config::ClientConfig; use rdkafka::consumer::{BaseConsumer, Consumer, EmptyConsumerContext}; use rdkafka::message::BorrowedMessage; use rdkafka::message::Timestamp::*; use rdkafka::Message; use rocket::http::RawStr; use rocket::State; use scheduled_executor::ThreadPoolExecutor; use config::{ClusterConfig, Config}; use error::*; use metadata::ClusterId; use std::borrow::Cow; use std::collections::HashMap; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, RwLock}; use std::time::{Duration, Instant}; pub struct LiveConsumer { id: u64, cluster_id: ClusterId, topic: String, last_poll: RwLock<Instant>, consumer: BaseConsumer<EmptyConsumerContext>, active: AtomicBool, } impl LiveConsumer { fn new(id: u64, cluster_config: &ClusterConfig, topic: &str) -> Result<LiveConsumer> { let consumer = ClientConfig::new() .set("bootstrap.servers", &cluster_config.bootstrap_servers()) .set("group.id", &format!("kafka_view_live_consumer_{}", id)) .set("enable.partition.eof", "false") .set("api.version.request", "true") .set("enable.auto.commit", "false") .set("queued.max.messages.kbytes", "100") .set("fetch.message.max.bytes", "102400") .create::<BaseConsumer<_>>() .chain_err(|| "Failed to create rdkafka consumer")?; debug!("Creating live consumer for {}", topic); Ok(LiveConsumer { id, cluster_id: cluster_config.cluster_id.clone().unwrap(), consumer, active: AtomicBool::new(false), last_poll: RwLock::new(Instant::now()), topic: topic.to_owned(), }) } fn activate(&self) -> Result<()> { debug!("Activating live consumer for {}", self.topic); self.consumer .subscribe(vec![self.topic.as_str()].as_slice()) .chain_err(|| "Can't subscribe to specified topics")?; self.active.store(true, Ordering::Relaxed); Ok(()) } pub fn is_active(&self) -> bool { self.active.load(Ordering::Relaxed) } pub fn last_poll(&self) -> Instant { *self.last_poll.read().unwrap() } pub fn id(&self) -> u64 { self.id } pub fn cluster_id(&self) -> &ClusterId { &self.cluster_id } pub fn topic(&self) -> &str { &self.topic } fn poll(&self, max_msg: usize, timeout: Duration) -> Vec<BorrowedMessage> { let start_time = Instant::now(); let mut buffer = Vec::new(); *self.last_poll.write().unwrap() = Instant::now(); while Instant::elapsed(&start_time) < timeout && buffer.len() < max_msg { match self.consumer.poll(100) { None => {} Some(Ok(m)) => buffer.push(m), Some(Err(e)) => { error!("Error while receiving message {:?}", e); } }; } debug!( "{} messages received in {:?}", buffer.len(), Instant::elapsed(&start_time) ); buffer } } impl Drop for LiveConsumer { fn drop(&mut self) { debug!("Dropping consumer {}", self.id); } } type LiveConsumerMap = HashMap<u64, Arc<LiveConsumer>>; fn remove_idle_consumers(consumers: &mut LiveConsumerMap) { consumers.retain(|_, ref consumer| consumer.last_poll().elapsed() < Duration::from_secs(20)); } pub struct LiveConsumerStore { consumers: Arc<RwLock<LiveConsumerMap>>, _executor: ThreadPoolExecutor, } impl LiveConsumerStore { pub fn new(executor: ThreadPoolExecutor) -> LiveConsumerStore { let consumers = Arc::new(RwLock::new(HashMap::new())); let consumers_clone = Arc::clone(&consumers); executor.schedule_fixed_rate( Duration::from_secs(10), Duration::from_secs(10), move |_handle| { let mut consumers = consumers_clone.write().unwrap(); remove_idle_consumers(&mut *consumers); }, ); LiveConsumerStore { consumers, _executor: executor, } } fn get_consumer(&self, id: u64) -> Option<Arc<LiveConsumer>> { let consumers = self.consumers.read().expect("Poison error"); (*consumers).get(&id).cloned() } fn add_consumer( &self, id: u64, cluster_config: &ClusterConfig, topic: &str, ) -> Result<Arc<LiveConsumer>> { let live_consumer = LiveConsumer::new(id, cluster_config, topic) .chain_err(|| "Failed to create live consumer")?; let live_consumer_arc = Arc::new(live_consumer); match self.consumers.write() { Ok(mut consumers) => (*consumers).insert(id, live_consumer_arc.clone()), Err(_) => panic!("Poison error while writing consumer to cache"), }; live_consumer_arc .activate() .chain_err(|| "Failed to activate live consumer")?; Ok(live_consumer_arc) } pub fn consumers(&self) -> Vec<Arc<LiveConsumer>> { self.consumers .read() .unwrap() .iter() .map(|(_, consumer)| consumer.clone()) .collect::<Vec<_>>() } } #[derive(Serialize)] struct TailedMessage { partition: i32, offset: i64, key: Option<String>, created_at: Option<i64>, appended_at: Option<i64>, payload: String, } #[get("/api/tailer/<cluster_id>/<topic>/<id>")] pub fn topic_tailer_api( cluster_id: ClusterId, topic: &RawStr, id: u64, config: State<Config>, live_consumers_store: State<LiveConsumerStore>, ) -> Result<String> { let cluster_config = config.clusters.get(&cluster_id); if cluster_config.is_none() || !cluster_config.unwrap().enable_tailing { return Ok("[]".to_owned()); } let cluster_config = cluster_config.unwrap(); let consumer = match live_consumers_store.get_consumer(id) { Some(consumer) => consumer, None => live_consumers_store .add_consumer(id, cluster_config, topic) .chain_err(|| { format!( "Error while creating live consumer for {} {}", cluster_id, topic ) })?, }; if !consumer.is_active() { return Ok("[]".to_owned()); } let mut output = Vec::new(); for message in consumer.poll(100, Duration::from_secs(3)) { let key = message .key() .map(|bytes| String::from_utf8_lossy(bytes)) .map(|cow_str| cow_str.into_owned()); let mut created_at = None; let mut appended_at = None; match message.timestamp() { CreateTime(ctime) => created_at = Some(ctime), LogAppendTime(atime) => appended_at = Some(atime), NotAvailable => (), } let original_payload = message .payload() .map(|bytes| String::from_utf8_lossy(bytes)) .unwrap_or(Cow::Borrowed("")); let payload = if original_payload.len() > 1024 { format!( "{}...", original_payload.chars().take(1024).collect::<String>() ) } else { original_payload.into_owned() }; output.push(TailedMessage { partition: message.partition(), offset: message.offset(), key, created_at, appended_at, payload, }) } Ok(json!(output).to_string()) }
use rdkafka::config::ClientConfig; use rdkafka::consumer::{BaseConsumer, Consumer, EmptyConsumerContext}; use rdkafka::message::BorrowedMessage; use rdkafka::message::Timestamp::*; use rdkafka::Message; use rocket::http::RawStr; use rocket::State; use scheduled_executor::ThreadPoolExecutor; use config::{ClusterConfig, Config}; use error::*; use metadata::ClusterId; use std::borrow::Cow; use std::collections::HashMap; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, RwLock}; use std::time::{Duration, Instant}; pub struct LiveConsumer { id: u64, cluster_id: ClusterId, topic: String, last_poll: RwLock<Instant>, consumer: BaseConsumer<EmptyConsumerContext>, active: AtomicBool, } impl LiveConsumer { fn new(id: u64, cluster_conf
} }; } debug!( "{} messages received in {:?}", buffer.len(), Instant::elapsed(&start_time) ); buffer } } impl Drop for LiveConsumer { fn drop(&mut self) { debug!("Dropping consumer {}", self.id); } } type LiveConsumerMap = HashMap<u64, Arc<LiveConsumer>>; fn remove_idle_consumers(consumers: &mut LiveConsumerMap) { consumers.retain(|_, ref consumer| consumer.last_poll().elapsed() < Duration::from_secs(20)); } pub struct LiveConsumerStore { consumers: Arc<RwLock<LiveConsumerMap>>, _executor: ThreadPoolExecutor, } impl LiveConsumerStore { pub fn new(executor: ThreadPoolExecutor) -> LiveConsumerStore { let consumers = Arc::new(RwLock::new(HashMap::new())); let consumers_clone = Arc::clone(&consumers); executor.schedule_fixed_rate( Duration::from_secs(10), Duration::from_secs(10), move |_handle| { let mut consumers = consumers_clone.write().unwrap(); remove_idle_consumers(&mut *consumers); }, ); LiveConsumerStore { consumers, _executor: executor, } } fn get_consumer(&self, id: u64) -> Option<Arc<LiveConsumer>> { let consumers = self.consumers.read().expect("Poison error"); (*consumers).get(&id).cloned() } fn add_consumer( &self, id: u64, cluster_config: &ClusterConfig, topic: &str, ) -> Result<Arc<LiveConsumer>> { let live_consumer = LiveConsumer::new(id, cluster_config, topic) .chain_err(|| "Failed to create live consumer")?; let live_consumer_arc = Arc::new(live_consumer); match self.consumers.write() { Ok(mut consumers) => (*consumers).insert(id, live_consumer_arc.clone()), Err(_) => panic!("Poison error while writing consumer to cache"), }; live_consumer_arc .activate() .chain_err(|| "Failed to activate live consumer")?; Ok(live_consumer_arc) } pub fn consumers(&self) -> Vec<Arc<LiveConsumer>> { self.consumers .read() .unwrap() .iter() .map(|(_, consumer)| consumer.clone()) .collect::<Vec<_>>() } } #[derive(Serialize)] struct TailedMessage { partition: i32, offset: i64, key: Option<String>, created_at: Option<i64>, appended_at: Option<i64>, payload: String, } #[get("/api/tailer/<cluster_id>/<topic>/<id>")] pub fn topic_tailer_api( cluster_id: ClusterId, topic: &RawStr, id: u64, config: State<Config>, live_consumers_store: State<LiveConsumerStore>, ) -> Result<String> { let cluster_config = config.clusters.get(&cluster_id); if cluster_config.is_none() || !cluster_config.unwrap().enable_tailing { return Ok("[]".to_owned()); } let cluster_config = cluster_config.unwrap(); let consumer = match live_consumers_store.get_consumer(id) { Some(consumer) => consumer, None => live_consumers_store .add_consumer(id, cluster_config, topic) .chain_err(|| { format!( "Error while creating live consumer for {} {}", cluster_id, topic ) })?, }; if !consumer.is_active() { return Ok("[]".to_owned()); } let mut output = Vec::new(); for message in consumer.poll(100, Duration::from_secs(3)) { let key = message .key() .map(|bytes| String::from_utf8_lossy(bytes)) .map(|cow_str| cow_str.into_owned()); let mut created_at = None; let mut appended_at = None; match message.timestamp() { CreateTime(ctime) => created_at = Some(ctime), LogAppendTime(atime) => appended_at = Some(atime), NotAvailable => (), } let original_payload = message .payload() .map(|bytes| String::from_utf8_lossy(bytes)) .unwrap_or(Cow::Borrowed("")); let payload = if original_payload.len() > 1024 { format!( "{}...", original_payload.chars().take(1024).collect::<String>() ) } else { original_payload.into_owned() }; output.push(TailedMessage { partition: message.partition(), offset: message.offset(), key, created_at, appended_at, payload, }) } Ok(json!(output).to_string()) }
ig: &ClusterConfig, topic: &str) -> Result<LiveConsumer> { let consumer = ClientConfig::new() .set("bootstrap.servers", &cluster_config.bootstrap_servers()) .set("group.id", &format!("kafka_view_live_consumer_{}", id)) .set("enable.partition.eof", "false") .set("api.version.request", "true") .set("enable.auto.commit", "false") .set("queued.max.messages.kbytes", "100") .set("fetch.message.max.bytes", "102400") .create::<BaseConsumer<_>>() .chain_err(|| "Failed to create rdkafka consumer")?; debug!("Creating live consumer for {}", topic); Ok(LiveConsumer { id, cluster_id: cluster_config.cluster_id.clone().unwrap(), consumer, active: AtomicBool::new(false), last_poll: RwLock::new(Instant::now()), topic: topic.to_owned(), }) } fn activate(&self) -> Result<()> { debug!("Activating live consumer for {}", self.topic); self.consumer .subscribe(vec![self.topic.as_str()].as_slice()) .chain_err(|| "Can't subscribe to specified topics")?; self.active.store(true, Ordering::Relaxed); Ok(()) } pub fn is_active(&self) -> bool { self.active.load(Ordering::Relaxed) } pub fn last_poll(&self) -> Instant { *self.last_poll.read().unwrap() } pub fn id(&self) -> u64 { self.id } pub fn cluster_id(&self) -> &ClusterId { &self.cluster_id } pub fn topic(&self) -> &str { &self.topic } fn poll(&self, max_msg: usize, timeout: Duration) -> Vec<BorrowedMessage> { let start_time = Instant::now(); let mut buffer = Vec::new(); *self.last_poll.write().unwrap() = Instant::now(); while Instant::elapsed(&start_time) < timeout && buffer.len() < max_msg { match self.consumer.poll(100) { None => {} Some(Ok(m)) => buffer.push(m), Some(Err(e)) => { error!("Error while receiving message {:?}", e);
random
[ { "content": "fn topic_tailer_panel(cluster_id: &ClusterId, topic: &str, tailer_id: u64) -> PreEscaped<String> {\n\n let panel_head = html! {\n\n i class=\"fa fa-align-left fa-fw\" {} \"Messages\"\n\n };\n\n let panel_body = html! {\n\n div class=\"topic_tailer\" data-cluster=(cluster_id)...
Rust
src/ton_core/monitoring/ton_transaction_parser.rs
FlukerGames/ever-wallet-api
42dae96a1966f0dbae6aecfeb754607082a341e9
use anyhow::Result; use bigdecimal::BigDecimal; use nekoton::core::models::{MultisigTransaction, TransactionError}; use num_traits::FromPrimitive; use serde::{Deserialize, Serialize}; use ton_block::CommonMsgInfo; use ton_types::AccountId; use uuid::Uuid; use crate::ton_core::*; pub async fn parse_ton_transaction( account: UInt256, block_utime: u32, transaction_hash: UInt256, transaction: ton_block::Transaction, ) -> Result<CaughtTonTransaction> { let in_msg = match &transaction.in_msg { Some(message) => message .read_struct() .map_err(|_| TransactionError::InvalidStructure)?, None => return Err(TransactionError::Unsupported.into()), }; let address = MsgAddressInt::with_standart( None, ton_block::BASE_WORKCHAIN_ID as i8, AccountId::from(account), )?; let sender_address = get_sender_address(&transaction)?; let (sender_workchain_id, sender_hex) = match &sender_address { Some(address) => ( Some(address.workchain_id()), Some(address.address().to_hex_string()), ), None => (None, None), }; let message_hash = in_msg.hash()?.to_hex_string(); let transaction_hash = Some(transaction_hash.to_hex_string()); let transaction_lt = BigDecimal::from_u64(transaction.lt); let transaction_scan_lt = Some(transaction.lt as i64); let transaction_timestamp = block_utime; let messages = Some(serde_json::to_value(get_messages(&transaction)?)?); let messages_hash = Some(serde_json::to_value(get_messages_hash(&transaction)?)?); let fee = BigDecimal::from_u128(compute_fees(&transaction)); let value = BigDecimal::from_u128(compute_value(&transaction)); let balance_change = BigDecimal::from_i128(nekoton_utils::compute_balance_change(&transaction)); let multisig_transaction_id = nekoton::core::parsing::parse_multisig_transaction(&transaction) .and_then(|transaction| match transaction { MultisigTransaction::Send(_) => None, MultisigTransaction::Confirm(transaction) => Some(transaction.transaction_id as i64), MultisigTransaction::Submit(transaction) => Some(transaction.trans_id as i64), }); let parsed = match in_msg.header() { CommonMsgInfo::IntMsgInfo(header) => { CaughtTonTransaction::Create(CreateReceiveTransaction { id: Uuid::new_v4(), message_hash, transaction_hash, transaction_lt, transaction_timeout: None, transaction_scan_lt, transaction_timestamp, sender_workchain_id, sender_hex, account_workchain_id: address.workchain_id(), account_hex: address.address().to_hex_string(), messages, messages_hash, data: None, original_value: None, original_outputs: None, value, fee, balance_change, direction: TonTransactionDirection::Receive, status: TonTransactionStatus::Done, error: None, aborted: is_aborted(&transaction), bounce: header.bounce, multisig_transaction_id, }) } CommonMsgInfo::ExtInMsgInfo(_) => { CaughtTonTransaction::UpdateSent(UpdateSentTransaction { message_hash, account_workchain_id: address.workchain_id(), account_hex: address.address().to_hex_string(), input: UpdateSendTransaction { transaction_hash, transaction_lt, transaction_scan_lt, transaction_timestamp: Some(transaction_timestamp), sender_workchain_id, sender_hex, messages, messages_hash, data: None, value, fee, balance_change, status: TonTransactionStatus::Done, error: None, multisig_transaction_id, }, }) } CommonMsgInfo::ExtOutMsgInfo(_) => return Err(TransactionError::InvalidStructure.into()), }; Ok(parsed) } fn get_sender_address(transaction: &ton_block::Transaction) -> Result<Option<MsgAddressInt>> { let in_msg = transaction .in_msg .as_ref() .ok_or(TransactionError::InvalidStructure)? .read_struct()?; Ok(in_msg.src()) } fn get_messages(transaction: &ton_block::Transaction) -> Result<Vec<Message>> { let mut out_msgs = Vec::new(); transaction .out_msgs .iterate(|ton_block::InRefValue(item)| { let fee = match item.get_fee()? { Some(fee) => { Some(BigDecimal::from_u128(fee.0).ok_or(TransactionError::InvalidStructure)?) } None => None, }; let value = match item.get_value() { Some(value) => Some( BigDecimal::from_u128(value.grams.0) .ok_or(TransactionError::InvalidStructure)?, ), None => None, }; let recipient = match item.header().get_dst_address() { Some(dst) => Some(MessageRecipient { hex: dst.address().to_hex_string(), base64url: nekoton_utils::pack_std_smc_addr(true, &dst, true)?, workchain_id: dst.workchain_id(), }), None => None, }; out_msgs.push(Message { fee, value, recipient, message_hash: item.hash()?.to_hex_string(), }); Ok(true) }) .map_err(|_| TransactionError::InvalidStructure)?; Ok(out_msgs) } fn get_messages_hash(transaction: &ton_block::Transaction) -> Result<Vec<String>> { let mut hashes = Vec::new(); transaction .out_msgs .iterate(|ton_block::InRefValue(item)| { hashes.push(item.hash()?.to_hex_string()); Ok(true) }) .map_err(|_| TransactionError::InvalidStructure)?; Ok(hashes) } fn compute_value(transaction: &ton_block::Transaction) -> u128 { let mut value = 0; if let Some(in_msg) = transaction .in_msg .as_ref() .and_then(|data| data.read_struct().ok()) { if let ton_block::CommonMsgInfo::IntMsgInfo(header) = in_msg.header() { value += header.value.grams.0; } } let _ = transaction.out_msgs.iterate(|out_msg| { if let CommonMsgInfo::IntMsgInfo(header) = out_msg.0.header() { value += header.value.grams.0; } Ok(true) }); value } fn compute_fees(transaction: &ton_block::Transaction) -> u128 { let mut fees = 0; if let Ok(ton_block::TransactionDescr::Ordinary(description)) = transaction.description.read_struct() { fees = nekoton_utils::compute_total_transaction_fees(transaction, &description) } fees } fn is_aborted(transaction: &ton_block::Transaction) -> bool { let mut aborted = false; if let Ok(ton_block::TransactionDescr::Ordinary(description)) = transaction.description.read_struct() { aborted = description.aborted } aborted } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct Message { pub fee: Option<BigDecimal>, pub value: Option<BigDecimal>, pub recipient: Option<MessageRecipient>, pub message_hash: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct MessageRecipient { pub hex: String, pub base64url: String, pub workchain_id: i32, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct Outputs { pub value: BigDecimal, pub recipient: OutputsRecipient, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct OutputsRecipient { pub hex: String, pub base64url: String, pub workchain_id: i64, }
use anyhow::Result; use bigdecimal::BigDecimal; use nekoton::core::models::{MultisigTransaction, TransactionError}; use num_traits::FromPrimitive; use serde::{Deserialize, Serialize}; use ton_block::CommonMsgInfo; use ton_types::AccountId; use uuid::Uuid; use crate::ton_core::*; pub async fn parse_ton_transaction( account: UInt256, block_utime: u32, transaction_hash: UInt256, transaction: ton_block::Transaction, ) -> Result<CaughtTonTransaction> { let in_msg = match &transaction.in_msg { Some(message) => message .read_struct() .map_err(|_| TransactionError::InvalidStructure)?, None => return Err(TransactionError::Unsupported.into()), }; let address = MsgAddressInt::with_standart( None, ton_block::BASE_WORKCHAIN_ID as i8, AccountId::from(account), )?; let sender_address = get_sender_address(&transaction)?; let (sender_workchain_id, sender_hex) = match &sender_address { Some(address) => ( Some(address.workchain_id()), Some(address.address().to_hex_string()), ), None => (None, None), }; let message_hash = in_msg.hash()?.to_hex_string(); let transaction_hash = Some(transaction_hash.to_hex_string()); let transaction_lt = BigDecimal::from_u64(transaction.lt); let transaction_scan_lt = Some(transaction.lt as i64); let transaction_timestamp = block_utime; let messages = Some(serde_json::to_value(get_messages(&transaction)?)?); let messages_hash = Some(serde_json::to_value(get_messages_hash(&transaction)?)?); let fee = BigDecimal::from_u128(compute_fees(&transaction)); let value = BigDecimal::from_u128(compute_value(&transaction)); let balance_change = BigDecimal::from_i128(nekoton_utils::compute_balance_change(&transaction)); let multisig_transaction_id = nekoton::core::parsing::parse_multisig_transaction(&transaction) .and_then(|transaction| match transaction { MultisigTransaction::Send(_) => None, MultisigTransaction::Confirm(transaction) => Some(transaction.transaction_id as i64), MultisigTransaction::Submit(transaction) => Some(transaction.trans_id as i64), }); let parsed = match in_msg.header() { CommonMsgInfo::IntMsgInfo(header) => { CaughtTonTransaction::Create(CreateReceiveTransaction { id: Uuid::new_v4(), message_hash, transaction_hash, transaction_lt, transaction_timeout: None, transaction_scan_lt, transaction_timestamp, sender_workchain_id, sender_hex, account_workchain_id: address.workchain_id(), account_hex: address.address().to_hex_string(), messages, messages_hash, data: None, original_value: None, original_outputs: None, value, fee, balance_change, direction: TonTransactionDirection::Receive, status: TonTransactionStatus::Done, error: None, aborted: is_aborted(&transaction), bounce: header.bounce, multisig_transaction_id, }) } CommonMsgInfo::ExtInMsgInfo(_) => { CaughtTonTransaction::UpdateSent(UpdateSentTransaction { message_hash, account_workchain_id: address.workchain_id(), account_hex: address.address().to_hex_string(), input: UpdateSendTransaction { transaction_hash, transaction_lt, transaction_scan_lt, transaction_timestamp: Some(transaction_timestamp), sender_workchain_id, sender_hex, messages, messages_hash, data: None, value, fee, balance_change, status: TonTransactionStatus::Done, error: None, multisig_transaction_id, }, }) } CommonMsgInfo::ExtOutMsgInfo(_) => return Err(TransactionError::InvalidStructure.into()), }; Ok(parsed) } fn get_sender_address(transaction: &ton_block::Transaction) -> Result<Option<MsgAddressInt>> { let in_msg = transaction .in_msg .as_ref() .ok_or(TransactionError::InvalidStructure)? .read_struct()?; Ok(in_msg.src()) } fn get_messages(transaction: &ton_block::Transaction) -> Result<Vec<Message>> { let mut out_msgs = Vec::new(); transaction .out_msgs .iterate(|ton_block::InRefValue(item)| { let fee = match item.get_fee()? { Some(fee) => { Some(BigDecimal::from_u128(fee.0).ok_or(TransactionError::InvalidStructure)?) } None => None, }; let value = match item.get_value() { Some(value) => Some( BigDecimal::from_u128(value.grams.0) .ok_or(TransactionError::InvalidStructure)?, ), None => None, }; let recipient = match item.header().get_dst_address() { Some(dst) => Some(MessageRecipient { hex: dst.address().to_hex_string(), base64url: nekoton_utils::pack_std_smc_addr(true, &dst, true)?, workchain_id: dst.workchain_id(), }), None => None, }; out_msgs.push(Message { fee, value, recipient, message_hash: item.hash()?.to_hex_string(), }); Ok(true) }) .map_err(|_| TransactionError::InvalidStructure)?; Ok(out_msgs) } fn get_messages_hash(transaction: &ton_block::Transaction) -> Result<Vec<String>> { let mut hashes = Vec::new(); transaction .out_msgs .iterate(|ton_block::InRefValue(item)| { hashes.push(item.hash()?.to_hex_string()); Ok(true) }) .map_err(|_| TransactionError::InvalidStructure)?; Ok(hashes) } fn compute_value(transaction: &ton_block::Transaction) -> u128 { let mut value = 0; if let Some(in_msg) = transaction .in_msg .as_ref() .and_then(|data| data.read_struct().ok()) { if let ton_block::CommonMsgInfo::IntMsgInfo(header) = in_msg.header() { value += header.value.grams.0; } } let _ = transaction.out_msgs.iterate(|out_msg| { if let CommonMsgInfo::IntMsgInfo(header) = out_msg.0.header() { value += header.value.grams.0; } Ok(true) }); value } fn compute_fees(transaction: &ton_block::Transaction) -> u128 { let mut fees = 0; if let Ok(ton_block::TransactionDescr::Ordinary(description)) = transaction.description.read_struct() { fees = nekoton_utils::compute_total_transaction_fees(transaction, &description) } fees }
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct Message { pub fee: Option<BigDecimal>, pub value: Option<BigDecimal>, pub recipient: Option<MessageRecipient>, pub message_hash: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct MessageRecipient { pub hex: String, pub base64url: String, pub workchain_id: i32, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct Outputs { pub value: BigDecimal, pub recipient: OutputsRecipient, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct OutputsRecipient { pub hex: String, pub base64url: String, pub workchain_id: i64, }
fn is_aborted(transaction: &ton_block::Transaction) -> bool { let mut aborted = false; if let Ok(ton_block::TransactionDescr::Ordinary(description)) = transaction.description.read_struct() { aborted = description.aborted } aborted }
function_block-full_function
[ { "content": "CREATE UNIQUE INDEX transactions_m_hash_account_wc_hex_idx ON transactions (message_hash, account_workchain_id, account_hex)\n\n WHERE direction = 'Send' AND transaction_hash IS NULL;\n", "file_path": "migrations/20211007170851_transactions.sql", "rank": 0, "score": 263855.109015261...
Rust
tests/list.rs
sunli829/async-graphql
175d8693fffff821a63eb7d7954c4091e91f7681
use std::{ cmp::Ordering, collections::{BTreeSet, HashSet, LinkedList, VecDeque}, }; use async_graphql::*; #[tokio::test] pub async fn test_list_type() { #[derive(InputObject)] struct MyInput { value: Vec<i32>, } struct Root { value_vec: Vec<i32>, value_hash_set: HashSet<i32>, value_btree_set: BTreeSet<i32>, value_linked_list: LinkedList<i32>, value_vec_deque: VecDeque<i32>, } #[Object] impl Root { async fn value_vec(&self) -> Vec<i32> { self.value_vec.clone() } async fn value_slice(&self) -> &[i32] { &self.value_vec } async fn value_linked_list(&self) -> LinkedList<i32> { self.value_linked_list.clone() } async fn value_hash_set(&self) -> HashSet<i32> { self.value_hash_set.clone() } async fn value_btree_set(&self) -> BTreeSet<i32> { self.value_btree_set.clone() } async fn value_vec_deque(&self) -> VecDeque<i32> { self.value_vec_deque.clone() } async fn value_input_slice(&self, a: Vec<i32>) -> Vec<i32> { a } async fn test_arg(&self, input: Vec<i32>) -> Vec<i32> { input } async fn test_input<'a>(&self, input: MyInput) -> Vec<i32> { input.value } } let schema = Schema::new( Root { value_vec: vec![1, 2, 3, 4, 5], value_hash_set: vec![1, 2, 3, 4, 5].into_iter().collect(), value_btree_set: vec![1, 2, 3, 4, 5].into_iter().collect(), value_linked_list: vec![1, 2, 3, 4, 5].into_iter().collect(), value_vec_deque: vec![1, 2, 3, 4, 5].into_iter().collect(), }, EmptyMutation, EmptySubscription, ); let json_value: serde_json::Value = vec![1, 2, 3, 4, 5].into(); let query = format!( r#"{{ valueVec valueSlice valueLinkedList valueHashSet valueBtreeSet valueVecDeque testArg(input: {0}) testInput(input: {{value: {0}}}) valueInputSlice1: valueInputSlice(a: [1, 2, 3]) valueInputSlice2: valueInputSlice(a: 55) }} "#, json_value ); let mut res = schema.execute(&query).await.data; if let Value::Object(obj) = &mut res { if let Some(Value::List(array)) = obj.get_mut("valueHashSet") { array.sort_by(|a, b| { if let (Value::Number(a), Value::Number(b)) = (a, b) { if let (Some(a), Some(b)) = (a.as_i64(), b.as_i64()) { return a.cmp(&b); } } Ordering::Less }); } } assert_eq!( res, value!({ "valueVec": vec![1, 2, 3, 4, 5], "valueSlice": vec![1, 2, 3, 4, 5], "valueLinkedList": vec![1, 2, 3, 4, 5], "valueHashSet": vec![1, 2, 3, 4, 5], "valueBtreeSet": vec![1, 2, 3, 4, 5], "valueVecDeque": vec![1, 2, 3, 4, 5], "testArg": vec![1, 2, 3, 4, 5], "testInput": vec![1, 2, 3, 4, 5], "valueInputSlice1": vec![1, 2, 3], "valueInputSlice2": vec![55], }) ); } #[tokio::test] pub async fn test_array_type() { struct Query; #[Object] impl Query { async fn values(&self) -> [i32; 6] { [1, 2, 3, 4, 5, 6] } async fn array_input(&self, values: [i32; 6]) -> [i32; 6] { assert_eq!(values, [1, 2, 3, 4, 5, 6]); values } } let schema = Schema::new(Query, EmptyMutation, EmptySubscription); assert_eq!( schema .execute("{ values }") .await .into_result() .unwrap() .data, value!({ "values": [1, 2, 3, 4, 5, 6] }) ); assert_eq!( schema .execute("{ arrayInput(values: [1, 2, 3, 4, 5, 6]) }") .await .into_result() .unwrap() .data, value!({ "arrayInput": [1, 2, 3, 4, 5, 6] }) ); assert_eq!( schema .execute("{ arrayInput(values: [1, 2, 3, 4, 5]) }") .await .into_result() .unwrap_err(), vec![ServerError { message: r#"Failed to parse "[Int!]": Expected input type "[Int; 6]", found [Int; 5]."# .to_owned(), source: None, locations: vec![Pos { line: 1, column: 22, }], path: vec![PathSegment::Field("arrayInput".to_owned())], extensions: None, }], ); }
use std::{ cmp::Ordering, collections::{BTreeSet, HashSet, LinkedList, VecDeque}, }; use async_graphql::*; #[tokio::test] pub async fn test_list_type() { #[derive(InputObject)] struct MyInput { value: Vec<i32>, } struct Root { value_vec: Vec<i32>, value_hash_set: HashSet<i32>, value_btree_set: BTreeSet<i32>, value_linked_list: LinkedList<i32>, value_vec_deque: VecDeque<i32>, } #[Object] impl Root { async fn value_vec(&self) -> Vec<i32> { self.value_vec.clone() } async fn value_slice(&self) -> &[i32] { &self.value_vec } async fn value_linked_list(&self) -> LinkedList<i32> { self.value_linked_list.clone() } async fn value_hash_set(&self) -> HashSet<i32> { self.value_hash_set.clone() } async fn value_btree_set(&self) -> BTreeSet<i32> { self.value_btree_set.clone() } async fn value_vec_deque(&self) -> VecDeque<i32> { self.value_vec_deque.clone() } async fn value_input_slice(&self, a: Vec<i32>) -> Vec<i32> { a } async fn test_arg(&self, input: Vec<i32>) -> Vec<i32> { input } async fn test_input<'a>(&self, input: MyInput) -> Vec<i32> { input.value } } let schema = Schema::new( Root { value_vec: vec![1, 2, 3, 4, 5], value_hash_set: vec![1, 2, 3, 4, 5].into_iter().collect(), value_btree_set: vec![1, 2, 3, 4, 5].into_iter().collect(), value_linked_list: vec![1, 2, 3, 4, 5].into_iter().collect(), value_vec_deque: vec![1, 2, 3, 4, 5].into_iter().collect(), }, EmptyMutation, EmptySubscription, ); let json_value: serde_json::Value = vec![1, 2, 3, 4, 5].into(); let query = format!( r#"{{ valueVec valueSlice valueLinkedList valueHashSet valueBtreeSet valueVecDeque testArg(input: {0}) testInput(input: {{value: {0}}}) valueInputSlice1: valueInputSlice(a: [1, 2, 3]) valueInputSlice2: valueInputSlice(a: 55) }} "#, json_value ); let mut res = schema.execute(&query).await.data; if let Value::Object(obj) = &mut res { if let Some(Value::List(array)) = obj.get_mut("valueHashSet") { array.sort_by(|a, b| { if let (Value::Number(a), Value::Number(b)) = (a, b) { if let (Some(a), Some(b)) = (a.as_i64(), b.as_i64()) { return a.cmp(&b); } } Ordering::Less }); } } assert_eq!( res, value!({ "valueVec": vec![1, 2, 3, 4, 5], "valueSlice": vec![1, 2, 3, 4, 5], "valueLinkedList": vec![1, 2, 3, 4, 5], "valueHashSet": vec![1, 2, 3, 4, 5], "valueBtreeSet": vec![1, 2, 3, 4, 5], "valueVecDeque": vec![1, 2, 3, 4, 5], "testArg": vec![1, 2, 3, 4, 5], "testInput": vec![1, 2, 3, 4, 5], "valueInputSlice1": vec![1, 2, 3], "valueInputSlice2": vec![55], }) ); } #[tokio::test] pub async fn test_array_type() { struct Query; #[Object] impl Query { async fn values(&self) -> [i32; 6] { [1, 2, 3, 4, 5, 6] } async fn array_input(&self, values: [i32; 6]) -> [i32; 6] { assert_eq!(values, [1, 2, 3, 4, 5, 6]); values } } let schema = Schema::new(Query, EmptyMutation, EmptySubscription); assert_eq!( schema .execut
e("{ values }") .await .into_result() .unwrap() .data, value!({ "values": [1, 2, 3, 4, 5, 6] }) ); assert_eq!( schema .execute("{ arrayInput(values: [1, 2, 3, 4, 5, 6]) }") .await .into_result() .unwrap() .data, value!({ "arrayInput": [1, 2, 3, 4, 5, 6] }) ); assert_eq!( schema .execute("{ arrayInput(values: [1, 2, 3, 4, 5]) }") .await .into_result() .unwrap_err(), vec![ServerError { message: r#"Failed to parse "[Int!]": Expected input type "[Int; 6]", found [Int; 5]."# .to_owned(), source: None, locations: vec![Pos { line: 1, column: 22, }], path: vec![PathSegment::Field("arrayInput".to_owned())], extensions: None, }], ); }
function_block-function_prefixed
[ { "content": "/// Parse a GraphQL query document.\n\n///\n\n/// # Errors\n\n///\n\n/// Fails if the query is not a valid GraphQL document.\n\npub fn parse_query<T: AsRef<str>>(input: T) -> Result<ExecutableDocument> {\n\n let mut pc = PositionCalculator::new(input.as_ref());\n\n\n\n let items = parse_defi...
Rust
src/olx_client/mod.rs
valpfft/alx
7069ec98458f4c16d8a6c5710f256fa0a08b4f09
use crate::parse_price; use crate::Offer; use select::document::Document; use select::predicate::{Attr, Class, Name, Predicate}; use std::collections::HashMap; static BASE_URL: &str = "https://www.olx.pl/oferty"; impl Offer { fn build_from_node(node: &select::node::Node) -> Offer { let title = node .find(Name("a").descendant(Name("strong"))) .next() .expect("Could not parse detailsLink text") .text(); let url = node .find(Name("a")) .next() .expect("Could not parse detailsLink link") .attr("href") .expect("Could not parse detailsLink href"); let price = match node.find(Class("price").descendant(Name("strong"))).next() { Some(node) => node.text(), None => "9999999".to_string(), }; Offer { title: title, price: parse_price(&price).expect("Olx: Could not parse price"), url: url.to_string(), } } } pub fn scrape(params: &HashMap<&str, &str>) -> Vec<Offer> { let mut collection = Vec::new(); let url = build_url(params); let pages = { let response = reqwest::get(&url).expect("Could not get url"); assert!(response.status().is_success()); let first_page = Document::from_read(response).expect("Could not parse first page"); let pager = first_page.find(Class("pager")).next(); let total_pages = match pager { Some(pager) => pager .find(Attr("data-cy", "page-link-last").descendant(Name("span"))) .next() .expect("Could not find last page") .text() .parse::<u32>() .expect("Could not parse last page number"), None => 1, }; let mut pages = Vec::new(); for page_number in 1..=total_pages { let page = get_page(format!("{}/?page={}", &url, page_number.to_string())); pages.push(page); } pages }; for page in pages { parse_page(page, &mut collection); } collection } fn build_url(params: &HashMap<&str, &str>) -> String { let mut url = format!( "{}/q-{}", BASE_URL, format_query(params.get("query").unwrap()) ); if params.contains_key("min_price") { add_filter( &format!( "search[filter_float_price:from]={}", params.get("min_price").unwrap() ), &mut url, ); } if params.contains_key("max_price") { add_filter( &format!( "search[filter_float_price:to]={}", params.get("max_price").unwrap() ), &mut url, ); } url } fn add_filter(filter: &str, url: &mut String) { match url.find("?") { Some(_) => url.push_str(&format!("&{}", filter)), None => url.push_str(&format!("?{}", filter)), }; } fn parse_page(response: reqwest::Response, result: &mut Vec<Offer>) { let page = Document::from_read(response).expect("Could not parse page"); for entry in page.find(Class("offer-wrapper")) { result.push(Offer::build_from_node(&entry)); } } fn get_page(url: String) -> reqwest::Response { let response = reqwest::get(&url).expect("Could not get url"); assert!(response.status().is_success()); response } fn format_query(query: &str) -> String { query.trim().replace(" ", "-") }
use crate::parse_price; use crate::Offer; use select::document::Document; use select::predicate::{Attr, Class, Name, Predicate}; use std::collections::HashMap; static BASE_URL: &str = "https://www.olx.pl/oferty"; impl Offer { fn build_from_node(node: &select::node::Node) -> Offer { let title = node .find(Name("a").descendant(Name("strong"))) .next() .expect("Could not parse detailsLink text") .text(); let url = node .find(Name("a")) .next() .expect("Could not parse detailsLink link") .attr("href") .expect("Could not parse detailsLink href"); let price = match node.find(Class("price").descendant(Name("strong"))).next() { Some(node) => node.text(), None => "9999999".to_string(), }; Offer { title: title, price: parse_price(&price).expect("Olx: Could not parse price"), url: url.to_string(), } } } pub fn scrape(params: &HashMap<&str, &str>) -> Vec<Offer> { let mut collection = Vec::new(); let url = build_url(params); let pages = { let response = reqwest::get(&url).expect("Could not get url"); assert!(response.status().is_success()); let first_page = Document::from_read(response).expect("Could not parse first page"); let pager = first_page.find(Class("pager")).next(); let total_pages = match pager { Some(pager) => pager .find(Attr("data-cy", "page-link-last").descendant(Name("span"))) .next() .expect("Could not find last page") .text() .parse::<u32>() .expect("Could not parse last page number"), None => 1, }; let mut pages = Vec::new(); for page_number in 1..=total_pages { let page = get_page(format!("{}/?page={}", &url, page_number.to_string())); pages.push(page); } pages }; for page in pages { parse_page(page, &mut collection); } collection } fn build_url(params: &HashMap<&str, &str>) -> String { let mut url = format!( "{}/q-{}", BASE_URL, format_query(params.get("query").unwrap()) ); if params.contains_key("min_price") { add_filter( &format!( "search[filter_float_price:from]={}", params.get("min_price").unwrap() ), &mut url, ); } if params.contains_key("max_price") { add_filter( &format!( "search[filter_float_price:to]={}", params.get("max_price").unwrap() ), &mut url, ); } url } fn add_filter(filter: &str, url: &mut String) { match url.find("?") { Some(_) => url.push_str(&format!("&{}", filter)), None => url.push_str(&format!("?{}", filter)), }; } fn parse_page(response: reqwest::Response, result: &mut Vec<Offer>) { let page = Document::from_read(response).expect("Could not parse page"); for entry in page.find(Class("offer-wrapper")) { result.push(Offer::build_from_node(&entry)); } }
fn format_query(query: &str) -> String { query.trim().replace(" ", "-") }
fn get_page(url: String) -> reqwest::Response { let response = reqwest::get(&url).expect("Could not get url"); assert!(response.status().is_success()); response }
function_block-full_function
[ { "content": "fn add_filter(filter: &str, url: &mut String) {\n\n match url.find(\"?\") {\n\n Some(_) => url.push_str(&format!(\"&{}\", filter)),\n\n None => url.push_str(&format!(\"?{}\", filter)),\n\n };\n\n}\n", "file_path": "src/allegro_lokalnie_client/mod.rs", "rank": 1, "sc...